Python Programming Language
Python is a cross-platform programming language, which means that it can run on multiple
platforms like Windows, macOS, Linux, and has even been ported to the Java and .NET
virtual machines. It is free and open-source.
Below are some facts about Python Programming Language:
1. Python is currently the most widely used multi-purpose, high-level programming
language.
2. Python allows programming in Object-Oriented and Procedural paradigms.
3. Python programs generally are smaller than other programming languages like Java.
Programmers have to type relatively less and indentation requirement of the language,
makes them readable all the time.
4. Python language is being used by almost all tech-giant companies like – Google,
Amazon, Facebook, Instagram, Dropbox, Uber… etc.
5. The biggest strength of Python is huge collection of standard library which can be used
for the following:
Machine Learning
GUI Applications (like Kivy, Tkinter, PyQt etc.)
Web frameworks like Django (used by YouTube, Instagram, Dropbox)
Image processing (like OpenCV, Pillow)
Web scraping (like Scrapy, BeautifulSoup, Selenium)
Test frameworks (creating and designing test cases)
Multimedia (is the use of computer to present & combine text, graphics, audio, and
video with links and tools that let the user navigate, interact, create and
communicate)
Scientific computing (is a field in mathematics that uses advanced computing
capabilities to understand and solve complex problems)
Text processing and many more
Python is a widely used general-purpose, high level programming language. It
was created by Guido van Rossum in 1991 and further developed by the
Python Software Foundation.
Beginning with Python programming
Online Interpreter:
1. http://codepad.org/
2. https://replit.com/
IDE:
Thonny IDE: https://thonny.org/
The Thonny IDE comes with the latest version of Python bundled in it. So you don't have to
install Python separately.
InstallPython Separately:
Download the latest version from python.org.
1. Run Python in Immediate mode
Once Python is installed, typing python in the command line will invoke the interpreter in
immediate mode. We can directly type in Python code, and press Enter to get the output.
Try typing in 1 + 1 and press enter. We get 2 as the output. This prompt can be used as a
calculator. To exit this mode, type quit () and press enter.
2. Run Python in the Development Environment (IDE)Integrated
We can use any text editing software to write a Python script file.
We just need to save it with the .py extension. But using an IDE can make our life a lot
easier. IDE is a piece of software that provides useful features like code hinting, syntax
highlighting and checking, file explorers, etc. to the programmer for application
development.
By the way, when you install Python, an IDE named IDLE is also installed. You can use
it to run Python on your computer. It's a decent IDE for beginners.
When you open IDLE, an interactive Python Shell is opened.
Now you can create a new file and save it with .py extension. For example, hello.py
Write Python code in the file and save it. To run the file, go to Run > Run Module or simply
click F5.
Your first Python Program
A simple program that displays “Hello, World!”. It's often used to illustrate the syntax of the
language.
Source Code
# This program prints Hello, world!
Print ('Hello, world!')
Output
Hello, world!
In this program, we have used the built-in print() function to print the string Hello, world! on
our screen.
Python Output Using print () function
We use the print () function to output data to the standard output device (screen). We can also
output data to a file, but this will be discussed later.
An example of its use is given below.
print ('This sentence is output to the screen')
Output
This sentence is output to the screen
Another example is given below:
a=5
print ('The value of a is', a)
Output
The value of a is 5
print (1, 2, 3, 4)
print (1, 2, 3, 4, sep='*')
print (1, 2, 3, 4, sep='#', end='&')
Output
1234
1*2*3*4
1#2#3#4&
The sep separator is used between the values. It defaults into a space character.After all
values are printed, end is printed. It defaults into a new line.
Python Input
To allow flexibility, we might want to take the input from the user. In Python, we have
the input () function to allow this. The syntax for input () is:
input ([prompt])
where prompt is the string we wish to display on the screen. It is optional.
>>>num = input ('Enter a number: ')
Enter a number: 10
>>>num
'10'
Here, we can see that the entered value 10 is a string, not a number. To convert this into a
number we can use int() or float () functions.
>>>int ('10')
10
>>>float ('10')
10.0
Output formatting
Sometimes we would like to format our output to make it look attractive. This can be done by
using the str. format () method. This method is visible to any string object.
>>>x = 5; y = 10
>>>print ('The value of x is {} and y is {}’. format (x, y))
The value of x is5and y is10
Here, the curly braces {} are used as placeholders. We can specify the order in which they are
printed by using numbers (tuple index).
print('I love {0} and {1}'.format('bread','butter'))
print('I love {1} and {0}'.format('bread','butter'))
Output
I love bread and butter
I love butter and bread
We can even use keyword arguments to format the string.
>>>print ('Hello {name}, {greeting}'.format(greeting = 'Good morning', name = 'xyz'))
Hello xyz, Good morning
We can also format strings like the old sprintf() style used in C programming language. We
use the % operator to accomplish this.
>>>x = 12.3456789
>>>print('The value of x is %3.2f' %x)
The value of x is12.35
>>>print('The value of x is %3.4f' %x)
The value of x is12.3457
Python Keywords
Keywords are the reserved words in Python.
We cannot use a keyword as a variable name, function name or any other identifier.
They are used to define the syntax and structure of the Python language.
In Python, keywords are case sensitive.
The number of keywords can slightly vary from one version to another version of
python.
You can always get the list of keywords in your current version by typing the
following in the prompt.
>>>import keyword
>>>print(keyword.kwlist)
Python Identifiers
An identifier is a name given to entities like class, functions, variables, etc. It helps to
differentiate one entity from another.
Rules for writing identifiers
Identifiers can be a combination of letters in lowercase (a to z) or uppercase (A to Z)
or digits (0 to 9) or an underscore _. Names like myClass, and var_1 are valid
example.
An identifier cannot start with a digit. 1variable is invalid, but variable1 is a valid
name.
Keywords cannot be used as identifiers.
We cannot use special symbols like !, @, #, $, % etc. in our identifier.
An identifier can be of any length.
Python Statement, Indentation and Comments
Python Statement
Instructions that a Python interpreter can execute are called statements.
For example, a = 1 is an assignment statement.
Multi-line statement
In Python, the end of a statement is marked by a newline character.
But we can make a statement extend over multiple lines with the line continuation
character (\).
For example:This is an explicit line continuation
a=1+2+3+\
4+5+6+\
7+8+9
In Python, line continuation is implied inside parentheses ( ), brackets [ ], and braces { }.
For instance, we can implement the above multi-line statement as:
a = (1 + 2 + 3 +
4+5+6+
7 + 8 + 9)
Here, the surrounding parentheses ( ) do the line continuationimplicitly. Same is the case
with [ ] and { }.
For example:
colors = ['red',
'blue',
'green']
We can also put multiple statements in a single line using semicolons, as follows:
a = 1; b = 2; c = 3
Python Indentation
Most of the programming languages like C, C++, and Java use braces { } to define a
block of code. Python, however, uses indentation.
Generally, four whitespaces are used for indentation and are preferred over tabs.
for i in range (1,11):
print(i)
if i == 5:
break
The enforcement of indentation in Python makes the code look neat and clean. This results in
Python programs that look similar and consistent.
Indentation can be ignored in line continuation, but it's always a good idea to indent. It makes
the code more readable. For example:
if True:
print('Hello')
a=5
and
ifTrue: print('Hello'); a = 5
both are valid and do the same thing, but the former style is clearer.
Incorrect indentation will result in IndentationError
Python Comments
In Python, we use the hash (#) symbol to start writing a comment.
It extends up to the newline character. Comments are for programmers to better understand a
program.
Python Interpreter ignores comments.
#This is a comment
#print out Hello
print('Hello')
Multi-line comments
We can have comments that extend up to multiple lines.
One way is to use the hash(#) symbol at the beginning of each line. For example:
#This is a long comment
#and it extends
#to multiple lines
Another way of doing this is to use triple quotes, either ''' or """.
These triple quotes are generally used for multi-line strings. But they can be used as a multi-
line comment as well.
"""This is also a
perfect example of
multi-line comments"""
Python Variables, Constants and Literals
Python Variables
A variable is a named location used to store data in the memory.
It is helpful to think of variables as a container that holds data that can be changed later in the
program.
For example,
number = 10
number = 10
number = 1.1
Initially, the value of number was 10. Later, it was changed to 1.1.
Note: In Python, we don't actually assign values to the variables. Instead, Python gives the
reference of the object(value) to the variable.
Assigning values to Variables in Python
You can use the assignment operator = to assign a value to a variable.
Example 1: Declaring and assigning value to a variable
website = "google.com"
print(website)
Output
google.com
In the above program, we assigned a value apple.com to the variable website. Then, we
printed out the value assigned to website i.e. google.com
Example 2: Changing the value of a variable
website = "google.com"
print(website)
# assigning a new value to website
website = "microsoft.com"
print(website)
Output
google.com
microsoft.com
Example 3: Assigning multiple values to multiple variables
a, b, c = 5, 3.2, "Hello"
print (a)
print (b)
print (c)
If we want to assign the same value to multiple variables at once, we can do this as:
x = y = z = "same"
print (x)
print (y)
print (z)
The second program assigns the same string to all the three variables x, y and z.
Python Constants
A Python Constant is a variable whose value cannot be changed throughout the program.
Certain values are fixed and are universally proven to be true. These values cannot be changed
over time. Such types of values are called as Constants. We can think of Python Constants as a
bag full of fruits, but these fruits cannot be removed or changed with other fruits.
Note – Unlike other programming languages, Python does not contain any constants. Instead,
Python provides us a Capitalized naming convention method. Any variable written in the Upper
case is considered as a Constant in Python.
Rules to be followed while declaring a Constant
1. Python Constants and variable names should contain a combination of lowercase (a-z) or
capital (A-Z) characters, numbers (0-9), or an underscore ( ).
2. When using a Constant name, always use UPPERCASE, For example, CONSTANT = 50.
3. The Constant names should not begin with digits.
4. Except for underscore(_), no additional special character (!, #, ^, @, $) is utilized when
declaring a constant.
5. We should come up with a catchy name for the python constants. VALUE, for example,
makes more sense than V. It simplifies the coding process.
Assigning Values to Constants
Constants are typically declared and assigned in a module in Python. In this case, the module is
a new file containing variables, functions, and so on that is imported into the main file.
Constants are written in all capital letters with underscores separating the words within the
module. We create a separate file for declaring constants. We then use this file to import the
constant module in the main.py file from the other file.
Python Literals
The data which is being assigned to the variables are called as Literal.
In Python, Literals are defined as raw data which is being assigned to the variables or
constants.
Let us understand this by looking at a simple example,
Here, we have declared a variable ‘str’, and the value assigned to it ‘How are you, Sam?’ is a
literal of type string.
Python supports various different types of Literals. Let us look at each one of them in
detail.
Numeric Literals
Numeric Literals are values assigned to the Variables or Constants which cannot be changed
i.e., they are immutable. There are a total of 3 categories in Numeric Literals. They are –
Integer, Float, and Complex.
Example
Output
To generate real and imaginary components of complex numbers, we utilize real literal (c.real)
and imaginary literal (c.imag), respectively.
String Literals
A string literal is a series of characters surrounded by quotation marks. For a string, we can use
single, double, or triple quotations. We can write multi-line strings or display them in the
desired format by using triple quotes. A single character surrounded by single or double
quotations is also known as a character literal.
Example
Output
Boolean Literals
A Boolean Literal has either of the 2 values – True or False. Where True is considered as 1 and
False is considered as 0.
Example
Output
True indicates a value of 1 in Python, while False represents a value of 0. Because 1 equals
True, the value of boolean1 is True. And as 1 does not equal False, the value of boolean2 is
False. Similarly, we can utilize True and False as values in numeric expressions.
Data Types, Expressions, Statements, and Control Flow: Introduction to
Python, statements, comments, keywords, variables, operators, data types,
type casting, Control Statements: If, If-else, nested If-else, break, continue,
pass, Looping Statements: range, while loop, for loop, nested loops, input and
output.
Data Types
Data Types
There are mainly four types of basic/primitive data types available
in Python
Numeric: int, float, and complex
Sequence: String, list, and tuple
Set
Dictionary (dict)
Str data type
A string is a sequence of characters enclosed within a single
quote or double quote.
Example: “Welcome”
Operations on string: searching inside the string, creating a
substring, splitting the string
Example:
String1 = "Welcome"
print(type(String1)) # <class 'str'>
# display string
print(String1) # ' Welcome '
# accessing 2nd character of a string
print(String1[1]) # e
#accessing last character of a string
Print(String1[-1])
Note: The string is immutable, i.e., it cannot be changed once
defined. You need to create a copy of it if you want to modify it.
#changing 2nd character from the string will give an error
String1[1] = ‘q’
TypeError: 'str' object does not support item assignment
Int data type
Python uses the int data type to represent whole integer values.
The Integer type in Python is represented using a int class.
You can store positive and negative integer numbers of any length
such as 235, -758, 235689741.
We can create an integer variable using the two ways
1. Directly assigning an integer value to a variable
2. Using a int() class.
# store int value
roll_no = 33
print("Roll number is:", roll_no) # output 33
print(type(roll_no)) # output class 'int'
# store integer using int() class
id = int(25)
print(id) # 25
print(type(id)) # class 'int'
You can also store integer values other than base 10 such as
Binary (base 2)
Octal (base 8)
Hexadecimal numbers (base 16)
# decimal int 16 with base 8
# Prefix with zero + letter o
octal_num = 0o20
print(octal_num) # 16
print(type(octal_num)) # class 'int'
# decimal int 16 with base 16
# Prefix with zero + letter x
hexadecimal_num = 0x10 # decimal equivalent of 21
print(hexadecimal_num) # 16
print(type(hexadecimal_num)) # class 'int'
# decimal int 16 with base 2
# Prefix with zero + letter b
binary_num = 0b10000 # decimal equivalent of 6
print(binary_num) # 16
print(type(binary_num)) # class 'int'
Float data type
To represent floating-point values or decimal values, we can use
the float data type.
The float type in Python is represented using a float class.
We can create a float variable using the two ways
1. Directly assigning a float value to a variable
2. Using a float() class.
# store a floating-point value
salary = 8000.456
print("Salary is :", salary) # 8000.456
print(type(salary)) # class 'float'
# store a floating-point value using float() class
num = float(54.75)
print(num) # 54.75
print(type(num)) # class 'float'
Floating-point values can be represented using the exponential
form, also called scientific notation.
The benefit of using the exponential form to represent floating-
point values is we can represent large values using less memory.
# exponential float
num1 = 1.22e4
print(num1) # 12200.0
print(type(num1)) # class 'float'
Complex data type
A complex number is a number with a real and an imaginary
component represented as a+bj where a and b contain integers
or floating-point values.
The complex type is generally used in scientific applications and
electrical engineering applications.
x = 9 + 8j # both value are int type
y = 10 + 4.5j # one int and one float
z = 11.2 + 1.2j # both value are float type
print(type(x)) # class 'complex'>
print(x) # (9+8j)
print(y) # (10+4.5j)
print(z) # (11.2+1.2j)
List data type
The Python List is an ordered collection (also known as
a sequence) of elements. List elements can be accessed, iterated,
and removed according to the order they inserted at the
creation time.
We use the list data type to represent groups of the element as a
single entity. For example: If we want to store all student’s names,
we can use list type.
1. The list can contain data of all data types such
as int, float, string
2. Duplicates elements are allowed in the list
3. The list is mutable which means we can modify the value of list
elements
Ordered
When we say that lists are ordered, it means that the items have a
defined order, and that order will not change.
If you add new items to a list, the new items will be placed at the end
of the list.
Changeable
The list is changeable, meaning that we can change, add, and remove
items in a list after it has been created.
Allow Duplicates
Since lists are indexed, lists can have items with the same value:
Example:
List1 = ["apple", "banana", "cherry", "apple", "cherry"]
print(list1)
We can create a list using the two ways
1. By enclosing elements in the square brackets [].
2. Using a list() class.
List Length
To determine how many items a list has, use the len() function:
print(len(list1))
List Items - Data Types
List items can be of any data type:
list1 = ["apple", "banana", "cherry"]
list2 = [1, 5, 7, 9, 3]
list3 = [True, False, False]
A list can contain different data types:
list1 = ["abc", 34, True, 40, "male"]
Negative Indexing
Negative indexing means start from the end
-1 refers to the last item, -2 refers to the second last item etc.
list1 = ["apple", "banana", "cherry"]
print(list1[-1])
Program:
my_list = ["xyz", "zyx", 20, 35.75]
# display list
print(my_list) # ['xyz ', ' zyx ', 20, 35.75]
print(type(my_list)) # class 'list'
# Accessing first element of list
print(my_list[0]) # 'xyz'
# slicing list elements
print(my_list[1:5]) # ['zyx', 20, 35.75]
# modify 2nd element of a list
my_list[1] = "wwe"
print(my_list[1]) # 'wwe'
# create list using a list class
my_list2 = list(["xyz", "zyx", 20, 35.75])
print(my_list2) # ["xyz", "zyx", 20, 35.75]
Tuple data type
Tuples are ordered collections of elements that are unchangeable.
The tuple is the same as the list, except the tuple is immutable
means we can’t modify the tuple once created.
In other words, we can say a tuple is a read-only version of the list.
For example: If you want to store the roll numbers of students
that you don’t change, you can use the tuple data type.
Note: Tuple maintains the insertion order and also, allows us to
store duplicate elements.
We can create a tuple using the two ways
1. By enclosing elements in the parenthesis ()
2. Using a tuple() class.
Example:
Tuple1 = ("apple", "banana", "cherry")
print(tuple1)
Tuple Items
Tuple items are ordered, unchangeable, and allow duplicate
values.
Tuple items are indexed, the first item has index [0], the second
item has index [1] etc.
Ordered
When we say that tuples are ordered, it means that the items have a
defined order, and that order will not change.
Unchangeable
Tuples are unchangeable, meaning that we cannot change, add or
remove items after the tuple has been created.
Allow Duplicates
Since tuples are indexed, they can have items with the same value:
Example:
tuple1 = ("apple", "banana", "cherry", "apple", "cherry")
print(tuple1)
Tuple Length
To determine how many items a tuple has, use the len() function:
tuple1 = ("apple", "banana", "cherry")
print(len(tuple1))
Create Tuple with One Item
To create a tuple with only one item, you have to add a comma after
the item, otherwise Python will not recognize it as a tuple.
tuple1 = ("apple",)
print(type(tuple))
#NOT a tuple
tuple1 = ("apple")
print(type(tuple))
Tuple Items - Data Types
Tuple items can be of any data type:
tuple1 = ("apple", "banana", "cherry")
tuple2 = (1, 5, 7, 9, 3)
tuple3 = (True, False, False)
A tuple can contain different data types:
tuple1 = ("xyz", 43, True, "male")
Program:
# create a tuple
my_tuple = (11, 24, 56, 88, 78)
print(my_tuple) # (11, 24, 56, 88, 78)
print(type(my_tuple)) # class 'tuple'
# Accessing 3rd element of a tuple
print(my_tuple[2]) # 56
# slice a tuple
print(my_tuple[2:7]) # (56, 88, 78)
# create a tuple using a tuple() class
my_tuple2 = tuple((10, 20, 30, 40))
print(my_tuple2) # (10, 20, 30, 40)
Tuple is immutable
A tuple is immutable means once we create a tuple, we can’t
modify it.
# create a tuple
my_tuple = (11, 24, 56, 88, 78)
# modify 2nd element of tuple
my_tuple[1] = 35
print(my_tuple)
# TypeError: 'tuple' object does not support item assignment
Dict data type
In Python, dictionaries are unordered collections of unique
values stored in (Key-Value) pairs. Use a dictionary data type to
store data as a key-value pair.
The dictionary type is represented using a dict class. For example, if
you want to store the name and roll number of all students, then
you can use the dict type.
In a dictionary, duplicate keys are not allowed, but the value can
be duplicated. If we try to insert a value with a duplicate key, the
old value will be replaced with the new value.
Dictionary has some characteristics which are listed below:
1. A heterogeneous (i.e., str, list, tuple) elements are allowed for
both key and value in a dictionary. But an object can be a key in
a dictionary if it is hashable.
2. The dictionary is mutable which means we can modify its
items.
3. Dictionary is unordered so we can’t perform indexing and
slicing.
We can create a dictionary using the two ways
1. By enclosing key and values in the curly brackets {}
2. Using a dict() class.
Program 1:
# create a dictionary
my_dict = {1: "arun", 2: "ravi", 3: "rohan"}
# display dictionary
print(my_dict) # {1: "arun", 2: "ravi", 3: "rohan"}
print(type(my_dict)) # class 'dict'
# create a dictionary using a dit class
my_dict = dict({1: "arun", 2: "ravi", 3: "rohan"})
# display dictionary
print(my_dict) # {1: "arun", 2: "ravi", 3: "rohan"}
print(type(my_dict)) # class 'dict'
# access value using a key name
print(my_dict[1]) # ravi
# change the value of a key
my_dict[1] = "ali"
print(my_dict[1]) # ali
Program 2:
# Python program for demonstrating dictionaries.
my_dict = {"Name": "Tom", "Age": 50, "Movie": "Mission
Impossible"}
print(my_dict)
print("Its data type:", type(my_dict))
Output:
{'Name': 'Tom', 'Age': 50, 'Movie': 'Mission Impossible'}
Its data type: <class 'dict'>
Accessing values of a dictionary
Values of a dictionary are accessed by referring to their keys.
# Python program for accessing values of a dictionary.
my_dict = {'Name': 'Tom', 'Age': 50, 'Movie': 'Mission
Impossible'}
print(my_dict["Name"])
print(my_dict["Age"])
print(my_dict["Movie"])
Output:
Tom
50
Mission Impossible
Count Length
To determine how many items a dictionary has, use
the len() function:
print(len(my_dict))
Type of dictionary object
Print(type(my_dict))
<class 'dict'>
Set data type
In Python, a set is an unordered collection of data items that are
unique. In other words, Python Set is a collection of elements (Or
objects) that contains no duplicate elements.
In Python, the Set data type used to represent a group of unique
elements as a single entity. For example, if we want to store
student ID numbers, we can use the set data type.
The Set data type in Python is represented using a set class.
We can create a Set using the two ways
1. By enclosing values in the curly brackets {}
2. Using a set() class.
The set data type has the following characteristics.
1. It is mutable which means we can change set items
2. Duplicate elements are not allowed
3. Heterogeneous (values of all data types) elements are allowed
4. Insertion order of elements is not preserved, so we can’t
perform indexing on a Set
Program 1
# create a set using curly brackets{,}
my_set = {100, 25.75, "xyz"}
print(my_set) # {25.75, 100, 'xyz'}
print(type(my_set)) # class 'set'
# create a set using set class
my_set = set({100, 25.75, "xyz"})
print(my_set) # {25.75, 100, 'xyz'}
print(type(my_set)) # class 'set'
# add element to set
my_set.add(300)
print(my_set) # {25.75, 100, 'Jessa', 300}
# remove element from set
my_set.remove(100)
print(my_set) # {25.75, 'Jessa', 300}
Set Items
Set items are unordered, unchangeable, and do not allow duplicate
values.
Unordered
Unordered means that the items in a set do not have a defined order.
Set items can appear in a different order every time you use them,
and cannot be referred to by index or key.
Unchangeable
Set items are unchangeable, meaning that we cannot change the
items after the set has been created, but we can remove items and
add new items.
Duplicates Not Allowed
Sets cannot have two items with the same value.
Example
Duplicate values will be ignored:
my_set = {"apple", "banana", "cherry", "apple"}
print(my_set)
Note: The values True and 1 are considered the same value in sets,
and are treated as duplicates:
my_set = {"apple", "banana", "cherry", True, 1, 2}
print(my_set)
Output:
{True, 2, 'banana', 'cherry', 'apple'}
Note: The values False and 0 are considered the same value in sets,
and are treated as duplicates:
my_set = {"apple", "banana", "cherry", False, True, 0}
print(my_set)
Output:
{False, True, 'cherry', 'apple', 'banana'}
Length of a Set
print(len(my_set))
Data Types
Set items can be of any data type:
set1 = {"apple", "banana", "cherry"}
set2 = {1, 5, 7, 9, 3}
set3 = {True, False, False}
print(set1)
print(set2)
print(set3)
A set with strings, integers and boolean values:
set1 = {"abc", 34, True, 40, "male"}
type()
sets are defined as objects with the data type 'set':
my_set = {"apple", "banana", "cherry"}
print(type(my_set))
Frozenset
The frozenset data type is used to create the immutable Set. Once
we create a frozenset, then we can’t perform any changes on it.
Use a frozenset() class to create a frozenset.
my_set = {11, 44, 75, 89, 56}
print(type(my_set)) # class 'set'
# creating frozenset
f_set = frozenset(my_set)
print(type(f_set)) # class 'frozenset'
Bool data type
In Python, to represent boolean values (True and False) we use the
bool data type. Boolean values are used to evaluate the value of the
expression.
For example, when we compare two values, the expression is
evaluated, and Python returns the boolean True or False.
Example
x = 25
y = 20
z=x>y
print(z) # True
print(type(z)) # class 'bool'
Bytes data type
The bytes data type represents a group of byte numbers just like an
array.
We use the bytes() constructor to create bytes type, which also
returns a bytes object. Bytes are immutable (Cannot be changed).
Use bytes data type if we want to handle binary data like images,
videos, and audio files.
Example
a = [9, 14, 17, 11, 78]
b = bytes(a)
print(type(b)) # class 'bytes'
print(b[0]) # 9
print(b[-1]) # 78
In bytes, allowed values are 0 to 256. If we are trying to use any
other values, then we will get a ValueError.
Example:
a = [999, 314, 17, 11, 78] # Gives error range must be in 0 to 256
b = bytes(a)
print(type(b))
# ValueError: bytes must be in range(0, 256)
bytearray
The bytearray data type same as the bytes type except bytearray
mutable (we can modify its elements).
The bytearray() constructor returns a bytearray object.
Example:
# create a bytearray
list1 = [9, 17, 11, 78]
b_array = bytearray(list1)
print(b_array)
print(type(b_array)) # class 'bytearray'
# modifying bytearray
b_array[1] = 99
print(b_array[1]) # 99
# iterate bytearray
for i in b_array:
print(i, end=" ") # 9 99 11 78
Range data type
In Python, The built-in function range() used to generate a
sequence of numbers from a start number up to the stop
number.
For example, If we want to represent the roll number from 1 to 20,
we can use the range() type. By default, it returns an iterator object
that we can iterate using a for loop.
Example:
# Generate integer numbers from 10 to 14
numbers = range(10, 15, 1)
print(type(numbers)) # class 'range'
# iterate range using for loop
for i in range(10, 15, 1):
print(i, end=" ")
# Output 10 11 12 13 14
Python Input: Take Input from User
Input ()
The input() function reads a line entered on a console or screen
by an input device such as a keyboard, converts it into a string.
# take three values from user
name = input("Enter Employee Name: ")
salary = input("Enter salary: ")
company = input("Enter Company name: ")
# Display all values on screen
print("\n")
print("Printing Employee Details")
print("Name", "Salary", "Company")
print(name, salary, company)
Example:
number = input("Enter roll number ")
name = input("Enter age ")
print("\n")
print('Roll number:', number, 'Name:', name)
print("Printing type of a input values")
print("type of number", type(number))
print("type of name", type(name))
Check user Input is a Number or String in Python
number1 = input("Enter number and hit enter ")
print("Printing type of input value")
print("type of number ", type(number1))
Take an Integer Number as input from User
# program to calculate addition of two input integer
numbers
# convert inout into int
first_number = int(input("Enter first number "))
second_number = int(input("Enter second number "))
print("\n")
print("First Number:", first_number)
print("Second Number:", second_number)
sum1 = first_number + second_number
print("Addition of two number is: ", sum1)
Take Float Number as a Input from User
marks = float(input("Enter marks "))
print("\n")
print("Student marks is: ", marks)
print("type is:", type(marks))
Get Multiple inputs from a User in One Line
In Python, it is possible to get multiple values from the user in one
line. We can accept two or three values from the user.
Split input string using split() get the value of individual input.
name, age, marks = input("Enter your Name, Age, Percentage
separated by space ").split()
print("\n")
print("User Details: ", name, age, marks)
How to Get a list of numbers as input from a user in
Python
Below are the simple steps to input a list of numbers in Python.
1. Use an input() function
Use an input() function to accept the list elements from a user in
the format of a string separated by space.
2. Use the split() function of the string class
Next, the split() method breaks an input string into a list.
In Python, the split() method divides a string into multiple
substrings based on a specified delimiter.
If no delimiter is provided, it defaults to splitting on whitespace.
3. Use for loop and range() function to iterate a user list
Now, access list elements using a for loop and range() function.
4. Convert each element of the list into a number
At the end, convert each element of a list to an integer using an
int() function. If you want a list of strings as input, skip this step.
Example: Get a list of numbers as input from a user and calculate the
sum of it
input_string = input('Enter elements of a list separated by space \n')
user_list = input_string.split()
print('string list: ', user_list)
# convert each item to int type
for i in range(len(user_list)):
# convert each item to int type
user_list[i] = int(user_list[i])
print('User list: ', user_list)
# Calculating the sum of list elements
print("Sum = ", sum(user_list))
Input a list using input() and range() function in Python
Let’s see how to accept a list as input without using
the split() method.
First, create an empty list.
Next, accept a list size from the user (i.e., the number of
elements in a list)
Next, run the loop till the size of a list using a for
loop and range() function
Now, use the input() function to receive a number from a user.
At the end, add the current number to the list using
the append() function
number_list = []
n = int(input("Enter the list size "))
print("\n")
for i in range(0, n):
print("Enter number at index", i, )
item = int(input())
number_list.append(item)
print("User list is ", number_list)
Accept Multiline input From a User
If the user tries to enter multiline input, it reads only the first line.
Because whenever the user presses the enter key, the input function
reads information provided by the user and stops execution.
We can use a loop. In each iteration of the loop, we can get input
strings from the user and join them. You can also concatenate each
input string using the + operator separated by newline (\n).
# list to store multi line input
# press enter two times to exit
data = []
print("Tell me about yourself")
while True:
line = input()
if line:
data.append(line)
else:
break
finalText = '\n'.join(data)
print("\n")
print("Final text input")
print(finalText)
Output in Python
Python has a built-in print() function to display output to the
standard output device like screen and console.
Example 1: Display output on screen
# take input
name = input("Enter Name: ")
# Display output
print('User Name:', name)
Example 2: Display Output by separating each value
name = input('Enter Name ')
zip_code = int(input('Enter zip code '))
street = input('Enter street name ')
house_number = int(input('Enter house number '))
# Display all values separated by hyphen
print(name, zip_code, street, house_number, sep="-")
Output Formatting
You can display output in various styles and formats using the
following functions.
str.format()
repr()
str.rjust(), str.ljust() , and str.center().
str.zfill()
The % operator can also use for output formatting
str.format() to format output
str.format(*args, **kwargs)
The str is the string on which the format method is called. It can
contain text or replacement fields delimited by braces {}.
Each replacement field contains either the numeric index of a
positional argument present in the format method or the name
of a keyword argument.
The format method returns a formatted string as an output. Each
replacement field gets replaced with the actual string value of the
corresponding argument present in the format method. i.e., args.
Example
print('FirstName - {0}, LastName - {1}'.format('Virat', 'Kohli'))
Note: Here {0} and {1} is the numeric index of a positional argument
present in the format method. i.e., {0} = Virat and {1} = Kohli.
Anything that not enclosed in braces {} is considered a plain literal
text.
Format Output String by its positions
firstName = input("Enter First Name ")
lastName = input("Enter Last Name ")
organization = input("Enter Organization Name ")
print("\n")
print('{0}, {1} works at {2}'.format(firstName, lastName, organization))
print('{1}, {0} works at {2}'.format(firstName, lastName, organization))
print('FirstName {0}, LastName {1} works at {2}'.format(firstName, lastName,
organization))
print('{0}, {1} {0}, {1} works at {2}'.format(firstName, lastName, organization))
Accessing Output String Arguments by name
name = input("Enter Name ")
marks = input("Enter marks ")
print("\n")
print('Student: Name: {firstName}, Marks:
{percentage}%'.format(firstName=name, percentage=marks))
Output Alignment by Specifying a Width
text = input("Enter text ")
print("\n")
# left aligned
print('{:<25}'.format(text))
# Right aligned
print('{:>25}'.format(text))
# centered
print('{:^25}'.format(text))
Specifying a Sign While Displaying Output Numbers
positive_number = float(input("Enter Positive Number "))
negative_number = float(input("Enter Negative Number "))
print("\n")
# sign '+' is for both positive and negative number
print('{:+f}; {:+f}'.format(positive_number, negative_number))
# sign '-' is only for negative number
print('{:f}; {:-f}'.format(positive_number, negative_number))
Display Output Number in Various Format
number = int(input("Enter number "))
print("\n")
# 'd' is for integer number formatting
print("The number is:{:d}".format(number))
# 'o' is for octal number formatting, binary and hexadecimal format
print('Output number in octal format : {0:o}'.format(number))
# 'b' is for binary number formatting
print('Output number in binary format: {0:b}'.format(number))
# 'x' is for hexadecimal format
print('Output number in hexadecimal format:
{0:x}'.format(number))
# 'X' is for hexadecimal format
print('Output number in HEXADECIMAL: {0:X}'.format(number))
Display Numbers as a float type
number = float(input("Enter float Number "))
print("\n")
# 'f' is for float number arguments
print("Output Number in The float type :{:f}".format(number))
# padding for float numbers
print('padding for output float number{:5.2f}'.format(number))
# 'e' is for Exponent notation
print('Output Exponent notation{:e}'.format(number))
# 'E' is for Exponent notation in UPPER CASE
print('Output Exponent notation{:E}'.format(number))
Output String Alignment
text = input("Enter String ")
print("\n")
print("Left justification", text.ljust(10, "*"))
print("Right justification", text.rjust(10, "*"))
print("Center justification", text.center(10, "*"))
Exercise
Exercise 1: Accept numbers from a user
Exercise 2: Display three string “Name”, “Is”, “James” as
“Name**Is**James”
Exercise 3: Convert Decimal number to octal using print() output
formatting
Exercise 4: Display float number with 2 decimal places using print()
Exercise 5: Accept a list of 5 float numbers as an input from the user
Exercise 6: Write all content of a given file into a new file by
skipping line number 5
Exercise 7: Accept any three string from one input() call
Exercise 8: Format variables using a string.format() method.
Exercise 9: Check file is empty or not
Exercise 10: Read line number 4 from the following file
Exercise 1. Write a program to accept two numbers from the
user and calculate multiplication.
num1 = int(input("Enter first number "))
num2 = int(input("Enter second number "))
res = num1 * num2
print("Multiplication is", res)
Exercise 2: Display three string “Name”, “Is”, “James” as
“Name**Is**James”
Expected Output:
For example: print('Name', 'Is', 'James') will display
Name**Is**James
print('My', 'Name', 'Is', 'James', sep='**')
Exercise 3: Convert Decimal number to octal
using print() output formatting
Given:
8
Expected Output
The octal number of decimal number 8 is 10
num = 8
print('%o' % num)
Exercise 4: Display float number with 2 decimal places using
print()
Given
num = 458.541315
Expected Output:
458.54
num = 458.541315
print('%.2f' % num)
Exercise 5: Accept a list of 5 float numbers as an input from the
user
Expected Output:
[78.6, 78.6, 85.3, 1.2, 3.5]
numbers = []
# 5 is the list size
# run loop 5 times
for i in range(0, 5):
print("Enter number at location", i, ":")
# accept float number from user
item = float(input())
# add it to the list
numbers.append(item)
print("User List:", numbers)
Exercise 6: Accept any three string from one input() call
Expected Output
Enter three string Virat Sachin Dhoni
Name1: Virat
Name2: Sachin
Name3: Dhoni
str1, str2, str3 = input("Enter three string").split()
print('Name1:', str1)
print('Name2:', str2)
print('Name3:', str3)
Exercise 7: Format variables using
a string.format() method.
Given
totalMoney = 1000
quantity = 3
price = 450
Expected Output: I have 1000 dollars so I can buy 3 football for
450.00 dollars.
quantity = 3
totalMoney = 1000
price = 450
statement1 = "I have {1} dollars so I can buy {0} football for {2:.2f}
dollars."
print(statement1.format(quantity, totalMoney, price))
Control Flow Statements
The flow control statements are divided into three categories
1. Conditional statements
2. Iterative statements.
3. Transfer statements
Conditional statements
In Python, condition statements act depending on whether a given
condition is true or false.
You can execute different blocks of codes depending on the outcome
of a condition.
Condition statements always evaluate to either True or False.
There are three types of conditional statements.
1. if statement
2. if-else
3. if-elif-else
4. nested if-else
If statement in Python
In control statements, the if statement is the simplest form. It takes a
condition and evaluates to either True or False.
If the condition is True, then the True block of code will be executed,
and if the condition is False, then the block of code is skipped, and the
controller moves to the next line
Syntax
if condition:
statement 1
statement 2
statement n
Program
number = 6
if number > 5:
# Calculate square
print(number * number)
print('Next lines of code')
If – else statement
The if-else statement checks the condition and executes the if block
of code when the condition is True, and if the condition is False, it
will execute the else block of code.
Syntax
if condition:
statement 1
else:
statement 2
Program
password = input('Enter password ')
if password == "galgotias@#29":
print("Correct password")
else:
print("Incorrect Password")
Chain multiple if statement in Python
In Python, the if-elif-else condition statement has an elif blocks to
chain multiple conditions one after another. This is useful when you
need to check multiple conditions.
With the help of if-elif-else we can make a tricky decision.
The elif statement checks multiple conditions one by one and if the
condition fulfills, then executes that code.
Syntax
def user_check(choice):
if condition-1: if choice == 1:
print("Admin")
statement 1 elif choice == 2:
elif condition-2: print("Editor")
elif choice == 3:
stetement 2 print("Guest")
else:
elif condition-3:
print("Wrong entry")
stetement 3
... user_check(1)
user_check(2)
else: user_check(3)
statement user_check(4)
Nested if-else statement
In Python, the nested if-else statement is an if statement inside
another if-else statement. It is allowed in Python to put any number
of if statements in another if statement.
Indentation is the only way to differentiate the level of nesting. The
nested if-else is useful when we want to make a series of decisions.
Syntax of the nested-if-else:
if conditon_outer:
if condition_inner:
statement of inner if
else:
statement of inner else:
statement of outer if
else:
Outer else
statement outside if block
Example: Find a greater number between two numbers.
num1 = int(input('Enter first number '))
num2 = int(input('Enter second number '))
if num1 >= num2:
if num1 == num2:
print(num1, 'and', num2, 'are equal')
else:
print(num1, 'is greater than', num2)
else:
print(num1, 'is smaller than', num2)
Single statement suites
Instead of writing a block after the colon, we can write a statement
immediately after the colon. Block contains only a single line
statement.
number = 56
if number > 0: print("positive")
else: print("negative")
Similar to the if statement, while loop also consists of a single
statement, we can place that statement on the same line.
x=1
while x <= 5: print(x, end=" "); x = x+1
for loop in Python
Using for loop, we can iterate any sequence or iterable variable. The
sequence can be string, list, dictionary, set, or tuple.
Fig: Flowchart of for loop
Syntax of for loop:
for element in sequence:
body of for loop
Example To display first ten numbers using for loop.
for i in range(1, 11):
print(i)
While loop in Python
In Python, the while loop statement repeatedly executes a code block
while a particular condition is true.
In a while-loop, every time the condition is checked at the
beginning of the loop, and if it is true, then the loop’s body gets
executed. When the condition became False, the controller comes out
of the block.
Fig: Flowchart of while loop
Syntax of while-loop
while condition :
body of while loop
Example: Calculate the sum of first ten numbers.
num = 10
sum = 0
i=1
while i <= num:
sum = sum + i
i=i+1
print("Sum of first 10 number is:", sum)
Break Statement in Python
The break statement is used inside the loop to exit out of the loop.
It is useful when we want to terminate the loop as soon as the
condition is fulfilled instead of doing the remaining iterations.
It reduces execution time. Whenever the controller encountered a
break statement, it comes out of that loop immediately.
Example of using a break statement
for num in range(10):
if num > 5:
print("stop processing.")
break
print(num)
Continue statement in python
The continue statement is used to skip the current iteration and
continue with the next iteration.
Example of a continue statement
for num in range(3, 8):
if num == 5:
continue
else:
print(num)
Pass statement in Python
The pass is the keyword in Python, which won’t do anything.
Sometimes there is a situation in programming where we need to
define a syntactically empty block.
We can define that block with the pass keyword.
A pass statement is a Python null statement. When the interpreter
finds a pass statement in the program, it returns no operation.
Nothing happens when the pass statement is executed.
It is useful in a situation where we are implementing new methods
or also in exception handling. It plays a role like a placeholder.
Example
months = ['January', 'June', 'March', 'April']
for mon in months:
pass
print(months)
Python Conditions and If statements
Python supports the usual logical conditions from mathematics:
Equals: a == b
Not Equals: a != b
Less than: a < b
Less than or equal to: a <= b
Greater than: a > b
Greater than or equal to: a >= b
Examples
If statement: With indentation
a = 33
b = 200
if b > a:
print("b is greater than a")
If statement, without indentation (will raise an error):
a = 33
b = 200
if b > a:
print("b is greater than a") # you will get an error
The elif keyword is Python's way of saying "if the previous conditions
were not true, then try this condition".
Examples
a = 33
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
Else
The else keyword catches anything which isn't caught by the
preceding conditions.
a = 200
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
else:
print("a is greater than b")
Short Hand If
If you have only one statement to execute, you can put it on the
same line as the if statement.
One line if statement
if a > b: print("a is greater than b")
Short Hand If ... Else
If you have only one statement to execute, one for if, and one for
else, you can put it all on the same line:
a = 2
b = 330
print("A") if a > b else print("B")
You can also have multiple else statements on the same line:
One line if else statement, with 3 conditions:
a = 330
b = 330
print("A") if a > b else print("=") if a == b else print("B")
And
The and keyword is a logical operator, and is used to combine
conditional statements:
Test if a is greater than b, AND if c is greater than a:
a = 200
b = 33
c = 500
if a > b and c > a:
print("Both conditions are True")
Or
The or keyword is a logical operator, and is used to combine
conditional statements:
Test if a is greater than b, OR if a is greater than c:
a = 200
b = 33
c = 500
if a > b or a > c:
print("At least one of the conditions is True")
Not
The not keyword is a logical operator, and is used to reverse the
result of the conditional statement:
Test if a is NOT greater than b:
a = 33
b = 200
if not a > b:
print("a is NOT greater than b")
Nested If
You can have if statements inside if statements, this is
called nested if statements.
x = 41
if x > 10:
print("Above ten,")
if x > 20:
print("and also above 20!")
else:
print("but not above 20.")
The pass Statement
if statements cannot be empty, but if you for some reason have
an if statement with no content, put in the pass statement to avoid
getting an error.
a = 33
b = 200
if b > a:
pass
Loop
While Loop
Print i as long as i is less than 6:
i = 1
while i < 6:
print(i)
i += 1
The break Statement
With the break statement we can stop the loop even if the while
condition is true:
Exit the loop when i is 3:
i = 1
while i < 6:
print(i)
if i == 3:
break
i += 1
The continue Statement
With the continue statement we can stop the current iteration, and
continue with the next:
Continue to the next iteration if i is 3:
i = 0
while i < 6:
i += 1
if i == 3:
continue
print(i)
The else Statement
With the else statement we can run a block of code once when the
condition no longer is true:
Print a message once the condition is false:
i = 1
while i < 6:
print(i)
i += 1
else:
print("i is no longer less than 6")
FOR LOOP
A for loop is used for iterating over a sequence (that is either a list, a
tuple, a dictionary, a set, or a string).
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
Note: The for loop does not require an indexing variable to set
beforehand.
Looping Through a String
Even strings are iterable objects, they contain a sequence of
characters:
for x in "banana":
print(x)
The break Statement
With the break statement we can stop the loop before it has looped
through all the items:
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
if x == "banana":
break
fruits = ["apple", "banana", "cherry"]
for x in fruits:
if x == "banana":
break
print(x)
The continue Statement
With the continue statement we can stop the current iteration of the
loop, and continue with the next:
fruits = ["apple", "banana", "cherry"]
for x in fruits:
if x == "banana":
continue
print(x)
The range() Function
To loop through a set of code a specified number of times, we can use
the range() function,
The range() function returns a sequence of numbers, starting from 0
by default, and increments by 1 (by default), and ends at a specified
number.
for x in range(6):
print(x)
The range() function defaults to 0 as a starting value, however it is
possible to specify the starting value by adding a parameter: range(2,
6), which means values from 2 to 6 (but not including 6):
for x in range(2, 6):
print(x)
The range() function defaults to increment the sequence by 1,
however it is possible to specify the increment value by adding a third
parameter: range(2, 30, 3):
for x in range(2, 30, 3):
print(x)
Else in For Loop
The else keyword in a for loop specifies a block of code to be executed
when the loop is finished:
Print all numbers from 0 to 5, and print a message when the loop has ended:
for x in range(6):
print(x)
else:
print("Finally finished!")
Break the loop when x is 3, and see what happens with the else block:
for x in range(6):
if x == 3: break
print(x)
else:
print("Finally finished!")
Nested Loops
A nested loop is a loop inside a loop.
The "inner loop" will be executed one time for each iteration of the
"outer loop":
adj = ["red", "big", "tasty"]
fruits = ["apple", "banana", "cherry"]
for x in adj:
for y in fruits:
print(x, y)
The pass Statement
for loops cannot be empty, but if you for some reason have a for loop
with no content, put in the pass statement to avoid getting an error.
for x in [0, 1, 2]:
pass
Data Types, Expressions, Statements, and Control Flow: Introduction to
Python, statements, comments, keywords, variables, operators, data types,
type casting, Control Statements: If, If-else, nested If-else, break, continue,
pass, Looping Statements: range, while loop, for loop, nested loops, input and
output.
Data Types
Data Types
There are mainly four types of basic/primitive data types available
in Python
Numeric: int, float, and complex
Sequence: String, list, and tuple
Set
Dictionary (dict)
Str data type
A string is a sequence of characters enclosed within a single
quote or double quote.
Example: “Welcome”
Operations on string: searching inside the string, creating a
substring, splitting the string
Example:
String1 = "Welcome"
print(type(String1)) # <class 'str'>
# display string
print(String1) # ' Welcome '
# accessing 2nd character of a string
print(String1[1]) # e
#accessing last character of a string
Print(String1[-1])
Note: The string is immutable, i.e., it cannot be changed once
defined. You need to create a copy of it if you want to modify it.
#changing 2nd character from the string will give an error
String1[1] = ‘q’
TypeError: 'str' object does not support item assignment
Int data type
Python uses the int data type to represent whole integer values.
The Integer type in Python is represented using a int class.
You can store positive and negative integer numbers of any length
such as 235, -758, 235689741.
We can create an integer variable using the two ways
1. Directly assigning an integer value to a variable
2. Using a int() class.
# store int value
roll_no = 33
print("Roll number is:", roll_no) # output 33
print(type(roll_no)) # output class 'int'
# store integer using int() class
id = int(25)
print(id) # 25
print(type(id)) # class 'int'
You can also store integer values other than base 10 such as
Binary (base 2)
Octal (base 8)
Hexadecimal numbers (base 16)
# decimal int 16 with base 8
# Prefix with zero + letter o
octal_num = 0o20
print(octal_num) # 16
print(type(octal_num)) # class 'int'
# decimal int 16 with base 16
# Prefix with zero + letter x
hexadecimal_num = 0x10 # decimal equivalent of 21
print(hexadecimal_num) # 16
print(type(hexadecimal_num)) # class 'int'
# decimal int 16 with base 2
# Prefix with zero + letter b
binary_num = 0b10000 # decimal equivalent of 6
print(binary_num) # 16
print(type(binary_num)) # class 'int'
Float data type
To represent floating-point values or decimal values, we can use
the float data type.
The float type in Python is represented using a float class.
We can create a float variable using the two ways
1. Directly assigning a float value to a variable
2. Using a float() class.
# store a floating-point value
salary = 8000.456
print("Salary is :", salary) # 8000.456
print(type(salary)) # class 'float'
# store a floating-point value using float() class
num = float(54.75)
print(num) # 54.75
print(type(num)) # class 'float'
Floating-point values can be represented using the exponential
form, also called scientific notation.
The benefit of using the exponential form to represent floating-
point values is we can represent large values using less memory.
# exponential float
num1 = 1.22e4
print(num1) # 12200.0
print(type(num1)) # class 'float'
Complex data type
A complex number is a number with a real and an imaginary
component represented as a+bj where a and b contain integers
or floating-point values.
The complex type is generally used in scientific applications and
electrical engineering applications.
x = 9 + 8j # both value are int type
y = 10 + 4.5j # one int and one float
z = 11.2 + 1.2j # both value are float type
print(type(x)) # class 'complex'>
print(x) # (9+8j)
print(y) # (10+4.5j)
print(z) # (11.2+1.2j)
List data type
The Python List is an ordered collection (also known as
a sequence) of elements. List elements can be accessed, iterated,
and removed according to the order they inserted at the
creation time.
We use the list data type to represent groups of the element as a
single entity. For example: If we want to store all student’s names,
we can use list type.
1. The list can contain data of all data types such
as int, float, string
2. Duplicates elements are allowed in the list
3. The list is mutable which means we can modify the value of list
elements
Ordered
When we say that lists are ordered, it means that the items have a
defined order, and that order will not change.
If you add new items to a list, the new items will be placed at the end
of the list.
Changeable
The list is changeable, meaning that we can change, add, and remove
items in a list after it has been created.
Allow Duplicates
Since lists are indexed, lists can have items with the same value:
Example:
List1 = ["apple", "banana", "cherry", "apple", "cherry"]
print(list1)
We can create a list using the two ways
1. By enclosing elements in the square brackets [].
2. Using a list() class.
List Length
To determine how many items a list has, use the len() function:
print(len(list1))
List Items - Data Types
List items can be of any data type:
list1 = ["apple", "banana", "cherry"]
list2 = [1, 5, 7, 9, 3]
list3 = [True, False, False]
A list can contain different data types:
list1 = ["abc", 34, True, 40, "male"]
Negative Indexing
Negative indexing means start from the end
-1 refers to the last item, -2 refers to the second last item etc.
list1 = ["apple", "banana", "cherry"]
print(list1[-1])
Program:
my_list = ["xyz", "zyx", 20, 35.75]
# display list
print(my_list) # ['xyz ', ' zyx ', 20, 35.75]
print(type(my_list)) # class 'list'
# Accessing first element of list
print(my_list[0]) # 'xyz'
# slicing list elements
print(my_list[1:5]) # ['zyx', 20, 35.75]
# modify 2nd element of a list
my_list[1] = "wwe"
print(my_list[1]) # 'wwe'
# create list using a list class
my_list2 = list(["xyz", "zyx", 20, 35.75])
print(my_list2) # ["xyz", "zyx", 20, 35.75]
Tuple data type
Tuples are ordered collections of elements that are unchangeable.
The tuple is the same as the list, except the tuple is immutable
means we can’t modify the tuple once created.
In other words, we can say a tuple is a read-only version of the list.
For example: If you want to store the roll numbers of students
that you don’t change, you can use the tuple data type.
Note: Tuple maintains the insertion order and also, allows us to
store duplicate elements.
We can create a tuple using the two ways
1. By enclosing elements in the parenthesis ()
2. Using a tuple() class.
Example:
Tuple1 = ("apple", "banana", "cherry")
print(tuple1)
Tuple Items
Tuple items are ordered, unchangeable, and allow duplicate
values.
Tuple items are indexed, the first item has index [0], the second
item has index [1] etc.
Ordered
When we say that tuples are ordered, it means that the items have a
defined order, and that order will not change.
Unchangeable
Tuples are unchangeable, meaning that we cannot change, add or
remove items after the tuple has been created.
Allow Duplicates
Since tuples are indexed, they can have items with the same value:
Example:
tuple1 = ("apple", "banana", "cherry", "apple", "cherry")
print(tuple1)
Tuple Length
To determine how many items a tuple has, use the len() function:
tuple1 = ("apple", "banana", "cherry")
print(len(tuple1))
Create Tuple with One Item
To create a tuple with only one item, you have to add a comma after
the item, otherwise Python will not recognize it as a tuple.
tuple1 = ("apple",)
print(type(tuple))
#NOT a tuple
tuple1 = ("apple")
print(type(tuple))
Tuple Items - Data Types
Tuple items can be of any data type:
tuple1 = ("apple", "banana", "cherry")
tuple2 = (1, 5, 7, 9, 3)
tuple3 = (True, False, False)
A tuple can contain different data types:
tuple1 = ("xyz", 43, True, "male")
Program:
# create a tuple
my_tuple = (11, 24, 56, 88, 78)
print(my_tuple) # (11, 24, 56, 88, 78)
print(type(my_tuple)) # class 'tuple'
# Accessing 3rd element of a tuple
print(my_tuple[2]) # 56
# slice a tuple
print(my_tuple[2:7]) # (56, 88, 78)
# create a tuple using a tuple() class
my_tuple2 = tuple((10, 20, 30, 40))
print(my_tuple2) # (10, 20, 30, 40)
Tuple is immutable
A tuple is immutable means once we create a tuple, we can’t
modify it.
# create a tuple
my_tuple = (11, 24, 56, 88, 78)
# modify 2nd element of tuple
my_tuple[1] = 35
print(my_tuple)
# TypeError: 'tuple' object does not support item assignment
Dict data type
In Python, dictionaries are unordered collections of unique
values stored in (Key-Value) pairs. Use a dictionary data type to
store data as a key-value pair.
The dictionary type is represented using a dict class. For example, if
you want to store the name and roll number of all students, then
you can use the dict type.
In a dictionary, duplicate keys are not allowed, but the value can
be duplicated. If we try to insert a value with a duplicate key, the
old value will be replaced with the new value.
Dictionary has some characteristics which are listed below:
1. A heterogeneous (i.e., str, list, tuple) elements are allowed for
both key and value in a dictionary. But an object can be a key in
a dictionary if it is hashable.
2. The dictionary is mutable which means we can modify its
items.
3. Dictionary is unordered so we can’t perform indexing and
slicing.
We can create a dictionary using the two ways
1. By enclosing key and values in the curly brackets {}
2. Using a dict() class.
Program 1:
# create a dictionary
my_dict = {1: "arun", 2: "ravi", 3: "rohan"}
# display dictionary
print(my_dict) # {1: "arun", 2: "ravi", 3: "rohan"}
print(type(my_dict)) # class 'dict'
# create a dictionary using a dit class
my_dict = dict({1: "arun", 2: "ravi", 3: "rohan"})
# display dictionary
print(my_dict) # {1: "arun", 2: "ravi", 3: "rohan"}
print(type(my_dict)) # class 'dict'
# access value using a key name
print(my_dict[1]) # ravi
# change the value of a key
my_dict[1] = "ali"
print(my_dict[1]) # ali
Program 2:
# Python program for demonstrating dictionaries.
my_dict = {"Name": "Tom", "Age": 50, "Movie": "Mission
Impossible"}
print(my_dict)
print("Its data type:", type(my_dict))
Output:
{'Name': 'Tom', 'Age': 50, 'Movie': 'Mission Impossible'}
Its data type: <class 'dict'>
Accessing values of a dictionary
Values of a dictionary are accessed by referring to their keys.
# Python program for accessing values of a dictionary.
my_dict = {'Name': 'Tom', 'Age': 50, 'Movie': 'Mission
Impossible'}
print(my_dict["Name"])
print(my_dict["Age"])
print(my_dict["Movie"])
Output:
Tom
50
Mission Impossible
Count Length
To determine how many items a dictionary has, use
the len() function:
print(len(my_dict))
Type of dictionary object
Print(type(my_dict))
<class 'dict'>
Set data type
In Python, a set is an unordered collection of data items that are
unique. In other words, Python Set is a collection of elements (Or
objects) that contains no duplicate elements.
In Python, the Set data type used to represent a group of unique
elements as a single entity. For example, if we want to store
student ID numbers, we can use the set data type.
The Set data type in Python is represented using a set class.
We can create a Set using the two ways
1. By enclosing values in the curly brackets {}
2. Using a set() class.
The set data type has the following characteristics.
1. It is mutable which means we can change set items
2. Duplicate elements are not allowed
3. Heterogeneous (values of all data types) elements are allowed
4. Insertion order of elements is not preserved, so we can’t
perform indexing on a Set
Program 1
# create a set using curly brackets{,}
my_set = {100, 25.75, "xyz"}
print(my_set) # {25.75, 100, 'xyz'}
print(type(my_set)) # class 'set'
# create a set using set class
my_set = set({100, 25.75, "xyz"})
print(my_set) # {25.75, 100, 'xyz'}
print(type(my_set)) # class 'set'
# add element to set
my_set.add(300)
print(my_set) # {25.75, 100, 'Jessa', 300}
# remove element from set
my_set.remove(100)
print(my_set) # {25.75, 'Jessa', 300}
Set Items
Set items are unordered, unchangeable, and do not allow duplicate
values.
Unordered
Unordered means that the items in a set do not have a defined order.
Set items can appear in a different order every time you use them,
and cannot be referred to by index or key.
Unchangeable
Set items are unchangeable, meaning that we cannot change the
items after the set has been created, but we can remove items and
add new items.
Duplicates Not Allowed
Sets cannot have two items with the same value.
Example
Duplicate values will be ignored:
my_set = {"apple", "banana", "cherry", "apple"}
print(my_set)
Note: The values True and 1 are considered the same value in sets,
and are treated as duplicates:
my_set = {"apple", "banana", "cherry", True, 1, 2}
print(my_set)
Output:
{True, 2, 'banana', 'cherry', 'apple'}
Note: The values False and 0 are considered the same value in sets,
and are treated as duplicates:
my_set = {"apple", "banana", "cherry", False, True, 0}
print(my_set)
Output:
{False, True, 'cherry', 'apple', 'banana'}
Length of a Set
print(len(my_set))
Data Types
Set items can be of any data type:
set1 = {"apple", "banana", "cherry"}
set2 = {1, 5, 7, 9, 3}
set3 = {True, False, False}
print(set1)
print(set2)
print(set3)
A set with strings, integers and boolean values:
set1 = {"abc", 34, True, 40, "male"}
type()
sets are defined as objects with the data type 'set':
my_set = {"apple", "banana", "cherry"}
print(type(my_set))
Frozenset
The frozenset data type is used to create the immutable Set. Once
we create a frozenset, then we can’t perform any changes on it.
Use a frozenset() class to create a frozenset.
my_set = {11, 44, 75, 89, 56}
print(type(my_set)) # class 'set'
# creating frozenset
f_set = frozenset(my_set)
print(type(f_set)) # class 'frozenset'
Bool data type
In Python, to represent boolean values (True and False) we use the
bool data type. Boolean values are used to evaluate the value of the
expression.
For example, when we compare two values, the expression is
evaluated, and Python returns the boolean True or False.
Example
x = 25
y = 20
z=x>y
print(z) # True
print(type(z)) # class 'bool'
Bytes data type
The bytes data type represents a group of byte numbers just like an
array.
We use the bytes() constructor to create bytes type, which also
returns a bytes object. Bytes are immutable (Cannot be changed).
Use bytes data type if we want to handle binary data like images,
videos, and audio files.
Example
a = [9, 14, 17, 11, 78]
b = bytes(a)
print(type(b)) # class 'bytes'
print(b[0]) # 9
print(b[-1]) # 78
In bytes, allowed values are 0 to 256. If we are trying to use any
other values, then we will get a ValueError.
Example:
a = [999, 314, 17, 11, 78] # Gives error range must be in 0 to 256
b = bytes(a)
print(type(b))
# ValueError: bytes must be in range(0, 256)
bytearray
The bytearray data type same as the bytes type except bytearray
mutable (we can modify its elements).
The bytearray() constructor returns a bytearray object.
Example:
# create a bytearray
list1 = [9, 17, 11, 78]
b_array = bytearray(list1)
print(b_array)
print(type(b_array)) # class 'bytearray'
# modifying bytearray
b_array[1] = 99
print(b_array[1]) # 99
# iterate bytearray
for i in b_array:
print(i, end=" ") # 9 99 11 78
Range data type
In Python, The built-in function range() used to generate a
sequence of numbers from a start number up to the stop
number.
For example, If we want to represent the roll number from 1 to 20,
we can use the range() type. By default, it returns an iterator object
that we can iterate using a for loop.
Example:
# Generate integer numbers from 10 to 14
numbers = range(10, 15, 1)
print(type(numbers)) # class 'range'
# iterate range using for loop
for i in range(10, 15, 1):
print(i, end=" ")
# Output 10 11 12 13 14
Python Programming
Relational (comparison) operators
Relational operators are also called comparison operators. It
performs a comparison between two values. It returns a
boolean True or False depending upon the result of the comparison.
Operator Description Example
It returns True if the x>y
> (Greater than) left operand is greater result is
than the right True
It returns True if the
x<y
< (Less than) left operand is less than
result is False
the right
It returns True if both x == y
= =(Equal to)
operands are equal result is False
It returns True if both x != y
!= (Not equal to)
operands are equal result is True
It returns True if the
>= (Greater than or left operand is greater x >= y
equal to) than or equal to the result is True
right
It returns True if the
<= (Less than or equal x <= y
left operand is less than
to) result is False
or equal to the right
x = 10
y=5
z=2
# > Greater than
print(x > y) # True
print(x > y > z) # True
# < Less than
print(x < y) # False
print(y < x) # True
# Equal to
print(x == y) # False
print(x == 10) # True
# != Not Equal to
print(x != y) # True
print(10 != x) # False
# >= Greater than equal to
print(x >= y) # True
print(10 >= x) # True
# <= Less than equal to
print(x <= y) # False
print(10 <= x) # True
Assignment operators
In Python, Assignment operators are used to assigning value to the
variable. Assign operator is denoted by = symbol.
For example, name = "Rahul" here, we have assigned the string
literal ‘Rahul’ to a variable name.
Operator Meaning Equivalent
= (Assign) a=5 Assign 5 to variable a=5
a
+= (Add and assign) a+=5 Add 5 to a and a = a+5
assign it as a new value
to a
-= (Subtract and assign) a-=5 Subtract 5 from a = a-5
variable a and assign it
as a new value to a
*= (Multiply and assign) a*=5 Multiply variable a a = a*5
by 5 and assign it as a
new value to a
/= (Divide and assign) a/=5 Divide variable a a = a/5
by 5 and assign a new
value to a
%= (Modulus and a%=5 Performs a = a%5
assign) modulus on two values
and assigns it as a new
value to a
**= (Exponentiation a**=5 Multiply a five a = a**5
and assign) times and assigns the
result to a
//= (Floor-divide and a//=5 Floor-divide a by a = a//5
assign) 5 and assigns the result
to a
a=4
b=2
a += b
print(a) # 6
a=4
a -= 2
print(a) # 2
a=4
a *= 2
print(a) # 8
a=4
a /= 2
print(a) # 2.0
a=4
a **= 2
print(a) # 16
a=5
a %= 2
print(a) # 1
a=4
a //= 2
print(a) # 2
Logical operators
Logical operators are useful when checking a condition is true or not.
Python has three logical operators. All logical operator returns a boolean
value True or False depending on the condition in which it is used.
Operator Description Example
and (Logical and) True if both the a and b
operands are True
or (Logical or) True if either of the a or b
operands is True
not (Logical not) True if the operand not a
is False
Logical and
print(True and False) # False
print(True and True) # True
print(False and False) # False
print(False and True) # false
# actual use in code
a=2
b=4
# Logical and
if a > 0 and b > 0:
# both conditions are true
print(a * b)
else:
print("Do nothing")
Logical or
print(True or False) # True
print(True or True) # True
print(False or False) # false
print(False or True) # True
# actual use in code
a=2
b=4
# Logical and
if a > 0 or b < 0:
# at least one expression is true so conditions is true
print(a + b) # 6
else:
print("Do nothing")
not (Logical not)
The logical not operator returns boolean True if the expression
is false.
print(not False) # True return complements result
print(not True) # True return complements result
# actual use in code
a = True
# Logical not
if not a:
# a is True so expression is False
print(a)
else:
print("Do nothing")
Membership operators
Python’s membership operators are used to check for membership of
objects in sequence, such as string, list, tuple. It checks whether the
given value or variable is present in a given sequence. If present, it
will return True else False.
In operator
It returns a result as True if it finds a given object in the sequence.
Otherwise, it returns False.
Program: Let’s check if the number 15 present in a given list using
the in operator.
my_list = [11, 15, 21, 29, 50, 70]
number = 15
if number in my_list:
print("number is present")
else:
print("number is not present")
Not in operator
It returns True if the object is not present in a given sequence.
Otherwise, it returns False.
Program:
my_tuple = (11, 15, 21, 29, 50, 70)
number = 35
if number not in my_tuple:
print("number is not present")
else:
print("number is present")
Identity operators
Use the Identity operator to check whether the value of two variables
is the same or not.
Identity operators are used to compare the objects, not if they are
equal, but if they are actually the same object, with the same
memory location:
Python has 2 identity operators is and is not.
is Operator:
Program 1: is operator
x = 10
y = 11
z = 10
print(x is y) # it compare memory address of x and y
print(x is z) # it compare memory address of x and z
Program 2: is operator
x = ["mango", "grapes"]
y = ["mango", "grapes"]
z=x
print(x is z)
# returns True because z is the same object as x
print(x is y)
# returns False because x is not the same object as y, even if they have the
same content
print(x == y)
# to demonstrate the difference between "is" and "==": this comparison
returns True because x is equal to y
is not Operator:
The is not the operator returns boolean values either True or False. It Return
True if the first value is not equal to the second value. Otherwise, it returns
False.
x = 10
y = 11
z = 10
print(x is not y) # it campare memory address of x and y
print(x is not z) # it campare memory address of x and z
Bitwise Operators
In Python, bitwise operators are used to performing bitwise operations on
integers. To perform bitwise, we first need to convert integer value to binary
(0 and 1) value.
The bitwise operator operates on values bit by bit, so it’s called bitwise. It
always returns the result in decimal format. Python has 6 bitwise operators
listed below.
Operator Name Description
& AND Sets each bit to 1 if both bits are 1
| OR Sets each bit to 1 if one of two bits is 1
^ XOR Sets each bit to 1 if only one of two bits is 1
~ NOT Inverts all the bits
<< Zero fill left shift Shift left by pushing zeros in from the right
and let the leftmost bits fall off
>> Signed right shift Shift right by pushing copies of the
leftmost bit in from the left, and let the
rightmost bits fall off
Bitwise “&”
It performs logical AND operation on the integer value after
converting an integer to a binary value and gives the result as a
decimal value.
Program:
a=7
b=4
c=5
print(a & b)
print(a & c)
print(b & c)
Integer Binary Value Operation Decimal Value
a=7 0111 a & b = 0100 4
b=4 0100 a & c = 0101 5
c=5 0101 b & c = 0100 4
Bitwise “|”
It performs logical OR operation on the integer value after
converting integer value to binary value and gives the result a
decimal value.
Program:
a=7
b=4
c=5
print(a | b)
print(a | c)
print(b | c)
Integer Binary Value Operation Decimal Value
a=7 0111 a | b = 0111 7
b=4 0100 a | c = 0111 7
c=5 0101 b | c = 0101 5
Bitwise “^”
It performs Logical XOR ^ operation on the binary value of a integer
and gives the result as a decimal value.
Program:
a=7
b=4
c=5
print(a ^ b)
print(a ^ c)
print(b ^ c)
Integer Binary Value Operation Decimal Value
a=7 0111 a ^ b = 0011 3
b=4 0100 a ^ c = 0010 2
c=5 0101 b ^ c = 0001 1
Bitwise 1’s complement ~
It performs 1’s complement operation. It inverts each bit of binary
value and returns the bitwise negation of a value as a result.
Program:
a=7
b=4
c=3
print(~a, ~b, ~c)
# Output -8 -5 -4
Integer Binary Value Operation Decimal Value
a=7 0111 ~a = 1000 -8
b=4 0100 ~b = 0101 -5
c=3 0011 ~c = 0100 -4
Example:
s = 12 = 1100
~s = ~1100
= -(1 + 1100)
= -(1101)
= -13
Bitwise left-shift <<
The left-shift << operator performs a shifting bit of value by a given
number of the place and fills 0’s to new positions.
print(4 << 2)
# Output 16
print(5 << 3)
# Output 40
Below is the example to understand better:
s = 12 = 0000 1100
s << 1 = 0001 1000 = 24
s << 2 = 0011 0000 = 48
Bitwise right-shift >>
The right-shift >> operator performs shifting a bit of value to the right
by a given number of places. Here some bits are lost.
print(4 >> 2)
# Output 1
print(5 >> 2)
# Output 1
Below is the example to understand better:
s = 10 = 0000 1010
s >> 1 = 0000 0101 = 5
1. Write the pseudocode and draw a flow chart to calculate the
sum and product of two numbers and display it.
Algorithm:
Step 1: Start
Step 2: Input A, B
Step 3: Sum = A + B
Step 4: Product = A * B
Step 5: Print Sum, Product
Step 6: Stop
Pseudocode:
BEGIN
READ A, B
ADD sum = A + B
MUL mul = A * B
PRINT sum
PRINT mul
END
Flowchart:
Program:
a = int (input())
b = int (input())
Sum = a+b
Mul = a*b
print ("The sum and product of {} and {} is : ".format (a,b), Sum, " ", Mul)
Program 2: Write a Python program to calculate simple interest based on user input
for principal amount, rate, and time. Provide a clear explanation of the formula and
calculations.
p= int (input ("Enter principle amount = "))
r = int (input ("Enter rate of interest = "))
t = int (input ("Enter time in years = "))
simple_interest = int ((p*r*t)/100)
print ("Simple Interest is : ", simple_interest)
3. Write a program that checks if a given number is even or odd.
Provide an explanation of the concept of even and odd numbers.
Take input from the user.
Method 1:
def even_odd(n):
if n%2==0:
return "No is even"
else:
return "No is odd"
n= int (input ("Enter the Number : "))
print (even_odd(n))
Method 2:
n = int (input ("Enter the number"))
if n%2==0:
print ("The given no is even")
else:
print ("The given no is odd")
4. Write a program that checks if a given number is even or odd.
Provide an explanation of the concept of even and odd numbers.
Take input from the user.
You should follow the following steps to determine whether a year is a leap year
or not.
1. If a year is evenly divisible by 4 means having no remainder then go to
next step. If it is not divisible by 4. It is not a leap year. For example: 1997
is not a leap year.
2. If a year is divisible by 4, but not by 100. For example: 2012, it is a leap
year. If a year is divisible by both 4 and 100, go to next step.
3. If a year is divisible by 100, but not by 400. For example: 1900, then it is
not a leap year. If a year is divisible by both, then it is a leap year. So 2000
is a leap year.
def CheckLeap(Year):
# Checking if the given year is leap year
if((Year % 400 == 0) or
(Year % 100 != 0) and
(Year % 4 == 0)):
print("Given Year is a leap Year");
# Else it is not a leap year
else:
print ("Given Year is not a leap Year")
# Taking an input year from user
Year = int(input("Enter the number: "))
# Printing result
CheckLeap(Year)
Program: # Simple Python program to print the Simple pyramid pattern
1. n = int(input("Enter the number of rows"))
2. # Here, we are declaring the integer variable to store the input rows
3. # Here, we are declaring an outer loop to handle number of rows
4. for i in range(0, n):
5. # Here, we are declaring an inner loop to handle number of columns
6. # Here, the values are changing according to outer loop
7. for j in range(0, i + 1):
8. # Here, we are declaring a for loop for printing stars
9. print("* ", end="")
10. # Here, we are giving the ending line after each row
11. print()
Program: Write a program to check whether an alphabet entered by the user is a vowel or a constant.
l = input("Input a letter of the alphabet: ")
if l in ('a', 'e', 'i', 'o', 'u'):
print("%s is a vowel." % l)
elif l == 'y':
print("Sometimes letter y stand for vowel, sometimes stand for
consonant.")
else:
print("%s is a consonant." % l)
Write a program to find all the prime numbers in a given range from the user.
num = int(input("Enter the number: "))
if num > 1:
# check for factors
for i in range(2,num):
if (num % i) == 0:
print(num,"is not a prime number")
print(i,"times",num//i,"is",num)
break
else:
print(num,"is a prime number")
# if input number is less than
# or equal to 1, it is not prime
else:
print(num,"is not a prime number")