Python Overview
Python Overview
Python Overview
1.2.2 Indentation.................................................................................................................................................................... 9
1.8 Functions...............................................................................................................................................................................48
1.8.1 Function Definitions and Function Calls ..........................................................................................................48
1.1.1 Download
The first and foremost important thing is to install Python; a user needs to download the latest version of
Python from the official website. The procedure for downloading is given below.
1. Visit the following link with the help of a web browser.
[Link]
2. On the web page, search for the latest setup file for the desired operating system.
3. Click on the link and download the setup file in the local drive of the computer.
1.1.2 Install
After downloading the setup file, it is required to be installed in the system. The procedure for that is
mentioned below.
1. Navigate to the setup file in the computer and select it.
1
3. Select the option “Run as administrator” from the context menu.
4. Then allow the setup file to make changes in the system by clicking the Yes button on the
appeared prompt.
6. Make sure that both the checkboxes at the bottom of the dialogue box are checked.
8. Subsequently, the process of the installation starts in the system as shown below.
2
9. The following message displays on the screen after the successful installation of the Python
environment.
10. Click the Close button, and then Python is ready to use.
The Python installer for Windows has an IDLE module by default. Thus, separate installation of IDLE is not
required for a Windows PC. The complete form of Python IDLE is Python Integrated Development and
Learning Environment. It is nothing but an IDE (Integrated development environment) for Python. It is
used to execute single instructions of Python, and it is capable of creating, editing, and executing short
or long Python scripts. In short, the Python IDLE is a full-fledged text editor to create Python programs or
scripts. It also supports various useful features such as auto-complete, highlight, smart indent, etc.
3
This window is called IDLE Shell or Python Shell. It is used to type a single line of instruction, and
it is used to execute that instruction directly there. For example, type “28028 / 77” on it and press
Enter key.
This instruction divides the first number by the second number and returns the result “364” in the
following line as displayed above. Similarly, whenever an instruction is entered in the shell, it
produces the output in the next line.
3. It is not convenient to write or edit a multi-line script directly on the shell. Instead, a separate
window is used for that—the procedure for opening that window is mentioned below.
On the menu bar, select File >> New File as mentioned below.
4
Alternatively, the keyboard shortcuts can be used with Ctrl + n.
In this window, any Python script can be written, saved, executed and edited.
5. The following code can be typed and executed to understand its working.
6. After typing the script, the next important step before the execution is to save the script. For that,
on the menu bar, select File >> Save As.
5
Use keyboard shortcut Ctrl + Shift + s as an alternative.
7. Instantaneously after that, the following dialogue box opens up on the screen.
Navigate to the desired location on the computer where the file is required to be saved.
8. After that, give an appropriate name to the file with the extension “.py” and click the Save button.
9. On the menu bar, select Run >> Run Module as shown below to execute the script.
Instead of this, the keyboard shortcut key F5 can be utilised for the same purpose.
6
10. Promptly after that, the script is started to execute. Besides, the output of the script is displayed
on the Python Shell, as highlighted below.
7
3. Immediately then, the desired file of the Python script opens up on the screen. Now, any change
can be made in the file. For example,
4. After making any change in the original file, it becomes necessary to save all the changes. To do
that, choose Save from the File menu as shown below.
5. Promptly, all the changes are saved in the file. After this, the script can be executed.
8
A single statement in multiple lines: It is not compulsory that a statement must be fit in a single line. A
lengthy statement is required to span over more than one line to make the code much more readable on
many occasions. A single statement is written in multiple lines using the “\” backslash symbol. For example,
a = 23
b = 87
if a > 20 and \
b < 120 and \
b != 0 and \
a != b :
c = a + b
print("The sum of these two numbers: ", c)
In this example, all four comparisons (i.e. a > 20, b < 120, b != 0 and a != b) is just a part of the single
Python statement, but it spans over four separate lines because of the backslash character. Bear in mind
that the backslash character is not needed when the expression is closed within parentheses ( ), square
brackets [ ] or curly braces { }. For example,
print("Python is free and open-source.",
"It is a high-level programming language.",
"It is a general-purpose language.",
"It is an interactive language.",
"It is an interpreter based language.")
The above example also shows that multiple strings can be printed in a single print statement, provided
that each string must be separated by one another by a comma.
Multiple statements in a single line: Conversely, a single line can accommodate more than one Python
statement. It can be accomplished by putting the “;” semicolon character at the end of each statement.
Commonly, it is used to show short statements in a single line. For example,
a = 23; print("Value of a: ", a); b = 87; print("Value of b: ", b)
c = a + b; print("The sum of a and b: ", c)
1.2.2 Indentation
The spaces or tabs at the beginning of a line are called indentations. In Python programming, the
indentation of lines is used to identify or distinguish a group or block statements. The number of spaces
and tabs in the indentation is not fixed or constant in Python. To qualify as a single block or group of
statements, the indentation of all lines of the statements must be of equal size. For example, in Python,
the body of functions, loops and classes contains a block or group of statements to execute when the set
condition is met. There are specific indentation rules in Python in order to define an error-free group of
statements, and those are mentioned below.
1. A group of Python statements starts after a colon “:” character and a keystroke of the Enter key.
2. The indentation of each line of a group must be the same, whether spaces or tabs.
3. Use only spaces or tabs in the indentation at a time. Abstain from using the combination of both
in an indentation.
9
In order to maintain consistency in the size of indentations, it is recommended to use only four spaces as
indentations throughout a program. Furthermore, a block or group of code can have one or more blocks
of statements inside it with another level of indentations. For example,
x = 25
if x > 0:
#1st group or block of statements
print("x is greater than zero.")
print("x is a positive number.")
#to check whether a is one or two digits number
if x >= 10:
#another group or block of statements within the 1st group
print("x is not a single-digit number")
print("x is either two or more digits number")
1.2.3 Comments
Comments are non-executable statements in a program because the compiler or interpreter ignores
them. They are just text or notes of explanation or annotation of a program statement or block of
statements. They reduce the complexity of codes for human understanding and boost an individual’s
speed to grasp the purpose of codes and their structure. As standard practice, programmers leave
comments to give information about a part of the program for all future references. This information
addresses the various aspects of codes. For example, it can describe what actions a code can perform;
steps are taken to control specific actions, or sequences of activities are arranged to accomplish a task.
A comment in the Python program starts with the # symbol and ends with a token of the end line character
(carriage return). There are three ways by which comments can be written: in a single separate line, in the
same line with a program statement and in multiple lines. However, there are two types of comments:
single-line comment and multi-line comment. The description of these two comments is mentioned
below.
1 Single Line Comment: As already explained, the single-line comment with the # symbol can be
used in two ways: in a separate line and the same line next to a program statement. For example,
#this is a single-line comment in the separate line
print('Hello World!') #this is a single-line comment in the same line
2 Multi-line Comment: As the name suggests, these comments span over more than one line. In
which, each line starts with # symbol like this,
#this is multi
#line comments which
#span over more than
#one line
print('Goodbye!')
Besides this, a multi-line comment can be added to the program within triple quotes. For example,
""" This is multi
line comments which
span over more than
one line """
10
print('Goodbye!')
1.3 Literals
In programming, the term literal is used to refer to a fixed value. Literals are raw data, which is used to
assign values to variables or constants. A literal can be anything, a number, string or character. In the
following example, the value 7 is a numeric literal.
Python supports numerous types of literals; the basic literals are described below.
1. Numeric Literals: It is immutable or unchangeable literal. They can be broadly divided into three
categories: integer, float and complex. For example,
#Integer Literals
b = 0b1101111 #Binary Literal
o = 0o157 #Octal Literal
d = 111 #Decimal Literal
h = 0x6F #Hexadecimal Literal
#Float Literal
p_float = 62.43 #Point Float
e_float = 6.023e23 #Exponent Float
#Complex Literal
z = 2 + 6.62j
11
#Character literal
c = "a"
print(s)
print(c)
print(multi-line_string)
3. Boolean literals: A Boolean literal can have any of the two values, either True or False. The True
and the False also can be represented as 1 and 0, respectively. For example,
p = (1 == True) #comparison
q = (1 == False) #Comparison
print("p is equal to", p)
print("q is equal to", q)
r = True + 9
s = False + 9
print("r is equal to", r)
print("s is equal to", s)
Output:
p is equal to True
q is equal to False
r is equal to 10
s is equal to 9
1.4 Variables
In programming, variables are used to store values or information in reserved memory locations. Thus,
variables make it possible to process the data using various logical or mathematical operations. To
understand this, one can consider a variable as a box that contains information such as numbers or strings.
This analogy has very striking similarities; for example, a box’s label is analogous to a variable’s name.
Likewise, stuff in the box is equivalent to the value of a variable.
Unlike many other programming languages, variables in Python are not required to be declared. It is
because Python is a dynamically typed language. Even a variable can be assigned any value regardless of
any previous type. For example,
12
1.4.1 Variable Naming Convention
The variable’s name can be short (like x, y, z, etc.) or long and descriptive (like age, name, etc.) depending
upon programmers' needs. There are specific rules in Python to name a variable. They are mentioned as
follows.
1. The variable name can only have alphanumeric (alphabet and number) characters and underscore
characters. The various combinations of these can be used to create numerous variable names.
2. The variable name must start with a letter (a to z or A to z) or underscore (_)
3. It is invalid to start the variable name with a number. However, the numbers can be used in the
name after the first letter.
4. The variable name is case sensitive. This means the uppercase and lowercase letters are
considered distinct letters. For example, “Cat” and “cat” are treated as different names. Therefore,
variables with different cases are also viewed as separate variables in Python.
For example,
#Example of valid variable names
FIRSTNAME = 'Kabir'
firstname = 'Kabir'
FirstName = 'Kabir'
_first_name = 'Kabir'
name1st = 'Kabir'
name_1st = 'Kabir'
name1 = 'Kabir'
print("Name:", name)
print("Age:", age)
print("Height:", height)
Output:
Name: Raju
Age: 12
13
Height: 58.7
Python also allows a single value to assign multiple variables at the same time. For example,
#simultaneous assignment of a value to more than one variable
x = y = z = 1947
print('x =', x)
print('y =', y)
print('x =', z)
Output:
x = 1947
y = 1947
x = 1947
1.5 Operators
Operators in a programming language are symbols of numerous mathematical, logical and other
operations. They dictate how to perform specific mathematical, logical, comparison or relational operation
on variables and produce results. Python supports various types of operators. There are two categories of
operators: Unary and Binary operators. Depending upon the number of operands on which an operator
can operate at a time, it can fall under either one category. An operand is a variable or data on which an
operator acts. A unary operator operates on operands at a time. There are not too many numbers.
Operator Description
+ Unary plus
- Unary minus
~ Bit inversion
For example,
a = -2 # minus Unary Operator
b = +3 # Plus Unary Operator
c = a + b
print(" c =", c)
x = 5
print(" x =", x)
print("~x =", ~x) # Bit inversion Operator
Output:
c = 1
x = 5
~x = -6
Unlike unary, binary operators operate on two operands at a time. There are several different types of
binary operators available in Python, and those are mentioned below.
14
1.5.1 Arithmetic operators
The arithmetic operators are used to perform an arithmetical operation on two operands. The following
table describes each arithmetic operator briefly.
Operator Description
+ It is used to add two or more numerical operands such as x+y, 3+5+4, etc.
- It is used to subtract a right operand from a left, for example, x – y.
* It is the multiplication operator, which is used to multiply numeric operands.
15
Operator Description Example Equivalent to
= It assigns the value (of the right operand) into the left operand. x =2 x=2
It adds both the right and left operand and assigns the result
+= x+=2 x = x+2
into the left operand.
It subtracts the right operand’s value from the left operand’s
-= x-=2 x = x-2
value and saves the result in the left operand.
It multiplies right and left operands and assigns the result to the
*= X*=2 x = x*2
left operand.
It divides the left operand’s value by the right operand’s value
/= x/=2 x = x/2
and saves the result in the left operand.
It assigns the reminder to the left operand after dividing the left
%= x%=2 x = x%2
operand by the right operand.
It divides the left operand by the right operand and rounds
//= down the result to the whole number. Eventually, it saves the x//=2 x = x//2
result in the left operand.
In which the left operand serves as the base and the right x = x**2
**= operand as the power. The result gets saved in the left operand. x**=2 or
x = x2
16
1.5.3 Comparison Operators
In a programming language, comparison operators are used to comparing the values of two operands or
variables. A comparison operator returns a Boolean: True or False. There are various types of comparison
operators available in Python. The following is a list of some essential comparison operators, along with
a brief description.
Operator Name Description Example
It checks whether an operand on the left is
> Greater than (75 > 50) = True
greater than an operand on the right.
It checks whether an operand on the left is
< Less than (75 < 50) = False
less than an operand on the right.
It checks whether an operand on the left is
Greater than or
>= greater than or equal to an operand on the (75 >= 50) = True
equal to
right.
It checks whether an operand on the left is
Less than or
<= less than or equal to an operand on the (75 <=50) = False
equal to
right.
== Is equal to It compares the equality of two operands. (50 ==75) = False
!= Not equal to It compares the inequality of two operands. (50 != 75) = True
17
a >= b is True
a <= b is False
a == b is False
a != b is True
18
The following example demonstrates how these operators work.
P = 'apple'
Q = 'apple'
print("P is not Q: ", P is not Q)
A = 5
B = 5
print("A is B:", A is B)
B = 9
print("A is B:", A is B)
print("The unique ID of B:", id(B))
Output:
P is not Q: False
A is B: True
The unique ID of A: 140724300089136
The unique ID of B: 140724300089136
A is B: False
The unique ID of B: 140724300089264
19
1.6 Data Structures
Data structures are fundamental concepts in computer science. They are just different ways of storing,
organising and managing data efficiently. These data structures provide ease in accessing and performing
numerous operations on the data. However, no single data structure is adequate to handle all data-related
problems. Thus, there are various data structures models available. These models are helpful in varying
requirements.
There are four basic built-in data structures in Python: lists, tuples, dictionaries and sets. These four
structures are good enough to help in the vast majority of cases. These structures can be categorised into
two categories. Sequences and mappings are those two categories. Both sequences and mappings are
finite sets of elements. The difference is the way by which the elements of these two categories can be
accessed. In cases of a sequence, an element can be accessed using numeric indexes such as [0]. On the
other hand, an element of mapping can be accessed through an arbitrarily defined index. Such indexes
can be anything, including numbers, strings, or a combination of both.
Lists and Tuples fall under the category of sequences. Apart from these, strings are also categorised as a
sequence. It is because lists, tuples and strings data structures are ordered sequences. There is only one
mapping type available in Python that is dictionaries. Unlike the rest, the individual elements of sets
cannot be accessed using indexes. This is because sets are collections of unordered elements wherein
each element of sets does have an index. Thus, sets do not fall under either of the categories. More
information about lists, tuples, dictionaries and sets is mentioned below.
1.6.1 Lists
A list is an ordered collection and sequences of different or the same types of elements. Lists are the most
versatile data structure available in Python. They are capable of storing heterogeneous data elements. For
instance, a list in Python can store numbers, Boolean, strings, characters, even another list and many more
things. Furthermore, lists are mutable. This means the elements of a list can be changed at any point in
time, even after creating the list.
Creating Lists
A list in Python is created by placing a sequence of elements in the square brackets [ ]. For example,
#create an empty list
mylist_1 = []
print(mylist_1)
Output:
[]
20
[12, True, 5, (2+6.62j), 'Newton', 'g', 9.8]
[3, 2, 'colour', 'Fruits', ['red', 'yellow', 'orange'], ['apple',
'mango', 'Orange']]
In this example, the operator used to select various parts of the list is called the slicing operator. Any
portion of a list can be selected with a correct combination of indexes with the slicing operator. The
21
following figure gives a visual understanding of sequencing with a list.
[2:6]
0 1 2 3 4 5 6 7 8
[-5:-2]
Apart from lists, other data structures can be sliced using this, such as tuple, string, etc.
Modifying lists
In several instances, it becomes compulsory to make changes in a list after its creation. Lists are mutable
data structures that mean each element of a list can be changed. To change an element or a group of
elements in a list, the assignment operator is needed to be used. For example,
#Create a list of major cities
city = ['Mumbai', 'Banglore', 'Calcutta', 'Hyderabad', 'Goa', 'Chennai']
print(city)
One or more elements can be added to the existing list using predefined function append() or extend()
respectively. For example,
#Create the list of major cities
city = ['Mumbai', 'Bengaluru', 'Kolkata ', 'Hyderabad', 'Pune', 'Chennai']
print(city)
22
Output:
['Mumbai', 'Bengaluru', 'Kolkata ', 'Hyderabad', 'Pune', 'Chennai']
['Mumbai', 'Bengaluru', 'Kolkata ', 'Hyderabad', 'Pune', 'Chennai',
'Ahmadabad']
['Mumbai', 'Bengaluru', 'Kolkata ', 'Hyderabad', 'Pune', 'Chennai',
'Ahmadabad', 'Surat', 'Jaipur', 'Lucknow', 'Kanpur', 'Nagpur', 'Indore']
Two lists can be combined using the + operator, and it is known as concatenation. Using the * operator,
an element of a list can be repeated multiple time within the list for example,
#create two lists of primary and secondary colour
colour = ['red', 'green', 'blue']
sec_colour = ['Yellow', 'magenta', 'cyan']
An element of a list, a group of elements of a list or an entire list can be deleted with the keyword del. To
do this, just specify the name of a list and the index number of the elements required to be deleted. For
example,
#create a list
grains = ['wheat', 'rye', 'triticale', 'oats', 'oat bran', 'brown rice
',
'flaxseed']
23
Output:
['rye', 'triticale', 'oats', 'oat bran', 'brown rice', 'flaxseed']
['rye', 'triticale', 'oats']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'grains' is not defined
Instead of del keywords, predefined functions such as pop() or remove() can be used to remove an
element from a list. pop() does not require to know the index of a list to remove. It removes and returns
the last element of a list when no index is provided to pop().On the contrary, in remove(), an element is
required to be passed instead of its index number in order to remove it from the list. Besides this, it does
not return anything. For example,
#create a list of wild animals
animals = ["elephant", "rhinoceros", "blackbuck", "tiger", "lion",
"leopard", "snow leopard", "wolf"]
#remove rhinoceros
print([Link](1))
print(animals)
Output:
['elephant', 'rhinoceros', 'blackbuck', 'tiger', 'lion', 'leopard',
'wolf']
wolf
['elephant', 'rhinoceros', 'blackbuck', 'tiger', 'lion', 'leopard']
blackbuck
['elephant', 'rhinoceros', 'tiger', 'lion', 'leopard']
1.6.2 Tuples
Tuples are also collections of heterogeneous or homogeneous elements such as numbers, strings,
booleans, characters, etc. A tuple can also contain another tuple or list in it. Similar to a list, a tuple is an
ordered sequence; it means that an element or a group of elements can be accessed with indices and the
slicing operator. Unlike lists, tuples are immutable. This indicates that a tuple cannot be changed once it
has been created. A tuple is formed by enclosing all elements within ( ) parentheses or round brackets,
and a comma separates each element. For example,
Creating Lists
#create an empty tuple
emptyTuple = ()
24
print(emptyTuple)
print(tuple_1[5])
print(tuple_1[2:])
Modifying Tuple
The tuple elements cannot be changed after they have been assigned, as tuples are immutable. However,
some elements can be changed if they themselves are mutable. Suppose a tuple contains a list as an
element; by definition, the tuple cannot change, but the list can be modified since it is a mutable data
structure. For example,
#create a tuple and embeds a list in it
colour = ("rainbow", ["Red", "Orange", "Yellow", "Green", "Blue",
25
"Indigo", "purple"])
print(colour)
1.6.3 Dictionaries
Dictionaries are collections of keys and values pairs enclosed within curly braces {}. The key and the value
in a pair are separated by a colon : from each other. At the same time, a comma is used to separate each
pair in a dictionary. For example,
myDict = {"Name": "Kabir", "Age": 14, "Grade": 8}
In the above example, the dictionary contains three pairs of value and key, as shown below.
,
The following points are needed to be remembered while creating a dictionary.
1. Each key must be unique and cannot be repeated in the dictionary.
2. Each key should be a single element or word.
3. A key is always immutable. Therefore, a string, number or tuple can be used as a key.
4. A list cannot be used as a key because it can be modified.
5. A value can be anything, such as a number, string, character, list, tuple, another dictionary, etc. It
can be none.
Like lists, dictionaries are mutable data structures. However, dictionaries are unordered collections of keys
and values, unlike lists and tuples. It means the numerical indices cannot be used to access any value of
a dictionary. The corresponding key of a value is used to do that. For example,
#Create a dictionary with a few pairs of key and value
student = {"name": "Kabir Malik", "std": 8, "height": 66.7,
"Gender": "M"}
print(student)
26
{'name': 'Kabir Malik', 'std': 8, 'height': 66.7, 'Gender': 'M'}
66.7
Kabir Malik
27
#delete an entire dictionary
del Food_Dict
Output:
Original Food_Dict{'Vegetable': 'broccoli', 'Fruit': 'grapes',
'Grain': 'wheat', 'Dairy': 'cheese', 'oil': 'olive oil'}
1.6.4 Sets
Sets are an ordered collection of different elements. Each element of a set must be unique, which means
it does not allow duplicate values. Besides, each element of a set is immutable; it means its value cannot
be changed once it has been defined. However, a set as a whole is mutable, which means elements can
be added or removed in a set. Python sets are used to implement the mathematical notion of a set. It
helps to perform mathematical operations such as union, intersection, etc. There are no indices attached
to the elements of a set. Therefore, no individual elements can be accessed, and no slicing operation can
be done.
Creating set
Like a dictionary, a set is created by enclosing all elements with the curly braces {} and each element is
separated by a comma. Alternatively, a built-in function set() can be used to create a set. The set()
function is used, especially when an empty set is required to be created because an empty set is not
possible to create with curly braces. Any attempt to create an empty set with a curly bracket always ends
in creating a dictionary. For example,
#create an empty set
mySet = set()
print(mySet)
28
Output:
set()
{'Thu', 'Mon', 'Tue', 'Wed', 'Sat', 'Sun', 'Fri'}
{'Mar', 'Feb', 'Jan'}
Note: The set is an unordered collection of elements. As a result, the elements appear in a different order
on each occasion. Consequently, the order of the set elements in the above program’s output keeps
changing with each new execution of the print() commands.
Modifying Set
Sets can be modified or changed because they are mutable. Individual elements cannot be accessed to
make changes with the help of indices as they are unordered collections of elements, unlike lists or tuples.
Nevertheless, one can add one or more elements to a set using two built-in functions or methods. These
functions are add() and update(). add() is used to add a single item in a set, whereas update() is used
to append more than items at the same time. For example,
#create a set
alphabet = {"a", "e", "i", "o", "u"}
print("Original set of the alphabet:", alphabet)
29
"h", "j", "k", "l", "m", "n", "p", "q",
"r", "s", "t", "v", "w", "x", "z")
print("Updated alphabet set", alphabet)
Output:
Original set of the alphabet: {'e', 'a', 'u', 'o', 'i'}
Updated alphabet set: {'e', 'a', 'y', 'u', 'o', 'i'}
Updated alphabet set {'f', 'x', 'a', 'y', 'c', 'u', 'p', 'h', 'i',
'g', 'k', 'n', 'v', 'j', 'o', 'b', 'm', 't', 'w', 'd', 'e', 'q', 'l',
'r', 'z', 's'}
Deleting Set
Similar to adding new items in an already existing set, an item can also be removed from the set using
two built-in methods or functions: remove() and discard(). The only difference between the two is that
remove() returns an error message if no element is available to remove from a set. On the contrary, the
discard() does not return anything when there is no item available in the set. For example,
#create a non-empty set
week = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"}
print(week)
#discard an element
[Link]("Sun")
print(week)
#remove an element
[Link]("Mon")
print(week)
30
Python Set Operations
1. Union of Sets
Union in Set theory is one of the fundamental operations by which all the elements of two sets combine
in a new set of distinct elements from both sets. Suppose there are two sets, A and B. Their union can be
understood with the following diagram’s help.
To perform union operation on two sets, either the | operator or the built-in function union() is used. For
example,
#create a set of even numbers
A = {2, 4, 6, 8, 10}
print("Set of Even Numbers: A = ", A)
2. Intersection of Sets
Like the union, it is also another critical and fundamental operation of Set theory. Intersection operation
is used to determine elements that are common between any two sets. The following diagram conveys
this notion.
31
With the help of it, a new set of common elements can be created. To perform this operation on two sets
the & operator is used. Alternatively, the built-in method or function intersection() can be used. For
example,
#create a set of even numbers
A = {2, 4, 6, 8, 10}
print("Set of Even Numbers: A = ", A)
3. Difference of Sets
This operation is used to create a new set that includes only those elements of a set present only in that
set alone but not in the other set. The visual representation of this operation is depicted in the following
diagram.
The - operator is used to take the difference. Alternatively, built-in function difference() can be used. For
example,
32
#create a set of even numbers
A = {2, 4, 6, 8, 10}
print("Set of Even Numbers: A = ", A)
Output:
▪ Equals: x == y
▪ Not Equals: x != y
▪ Greater than: x > y
▪ Less than: x < y
▪ Greater than or equal to: x >= y
▪ Less than or equal to: x <= y
▪ Logical and: x <= 10 and x >= 0
▪ Logical or: x <= 10 or x >= 0
33
When a condition turns out to be true, then all the corresponding statements are executed. On the other
hand, when the condition is false, then related statements are simply avoided without execution. Thus,
conditional statements are helpful in decision making in programs. The entire discussion of conditional
statements can be summarised in the following flow chart diagram.
There are a variety of conditional statements available in Python to cater to the requirements of different
levels of conditions.
A. if statements
In this, a set of statements executes only if a specified condition is true. If the condition is false, then those
statements cannot be executed. The keyword if is used to apply this condition. The syntax for an if
statement is as follows.
if condition:
# Statements to execute if the condition is true
The following example demonstrates the application of this conditional statement.
#create and assign a value to a variable
age = 21
34
# This Block of statements execute
#only if the condition is true
else:
#this block of statements Executes
#only if the condition is false
The following flowchart explains the execution flow of statements in an if ...else statement.
35
.
.
.
else:
#this block statement execute
#only if all above conditions are false
36
D. Nested if statements
A nested if statement is one if statement inside another if statement. Python also allows nested if
statements. The following flowchart diagram can be helpful to understand this.
From the above flowchart, it is clear that if the condition of the outer conditional statement is true, then
the condition of the inner conditional statement is tested. The nested if statement enables the program
to check more than one condition before executing corresponding block statements. It increases the
decision making capability of a program several-fold. Syntax of Nested if-else statement:
if (1st condition):
#these block statements execute
#only if the above condition is true
if (2nd condition 2):
#these block statements execute
#only if 1st and 2nd conditions are true
The following statements show a small application of this conditional statement.
#create and assign a value to a variable
age = 17
37
print("That means you are underage for voting")
print("You can vote after 18")
else:
print("Since you are not an Indian")
print("You cannot participate in any election")
Output:
You are only 17
1.7.2 Loops
In programming, loops are control structures used to execute certain sequences of statements until a
specific condition is met. Loops enable programmers to reuse a set of statements without writing the
same statements repeatedly in a program. Thus, it reduces the length of a program drastically and makes
it very small and brief.
Suppose a program wants to print a message 100 times; it is a daunting task in the absence of loops.
Because then, 100 print statements are required to accomplish this. Instead, if a program uses a loop, the
entire program summarises within a few code lines. There are various types of loops available in Python
to execute a set of statements many times, depending upon different conditions. This includes for loops,
while loops and nested loops. These loops are discussed below.
38
A. While loop
While loops are used to execute a set of statements repeatedly until a specific condition is satisfied, when
that condition becomes false, the loop stops and does not execute the corresponding statements. The
following flowchart depicts it working.
First, the specified condition is tested if it is true, then statements in the loop’s body are executed. After
that, it again tests the condition, whether it is true or false. If it is true, then it re-runs the statement in the
body. The same cycle will continue until the condition becomes false, then the flow of execution jumps to
the first statement after the loop.
Generally, it is used when a programmer does not know beforehand how many times a set of statements
in the loop’s body needs to be executed. The syntax of a while loop in Python is mentioned below.
while expression:
statement(s)
Its syntax does not have many components, and it is relatively simple and straightforward. The while
loop‘s condition expression follows the keyword while. Below it, each statement must be mentioned with
the standard indentation, which defines the loop’s body. The following example demonstrates the usage
of a while loop.
#create a variable and assign one to it
counter = 0
39
Sorry! I will not do it again
Sorry! I will not do it again
Sorry! I will not do it again
Sorry! I will not do it again
Sorry! I will not do it again
Sorry! I will not do it again
Sorry! I will not do it again
Sorry! I will not do it again
B. For loop
For loops are used to iterate over each item of various sequences such as strings, lists, tuples, dictionaries
and sets. The following flowchart diagram depicts the working of for loops.
The program given below shows the application of a for loop in a program.
40
#Create a loop to print grocery list
for item in grocery_list:
print(counter, ".", item)
counter += 1
Output:
1 . rice
2 . flour
3 . lentils
4 . ['tea', 'sugar']
5 . spices
6 . milk
7 . oil
8 . nuts
9 . cleaning products
10 . snacks
On several occasions, data structures such as strings, tuples, lists, etc., do not naturally fit into programs.
However, the need of executing a set of statements repeatedly over a specified number of times using a
for loop is indispensable in the program. As explained, a for loop cannot run without a sequential data
structure. It means programs devoid of sequential data structures cannot use for loops to iterate specific
sets of instructions. The built-in method range() is used to solve such problems. The range method works
well with for loops without any sequences such as strings, tuples, lists etc.
The range() method returns any desired sequence of numbers, and this sequence starts from any
specified number and ends at another specified number. In this function, successive increments of each
sequence can be established. The following syntax structure gives an intuitive understanding of it.
If the “from” is not specified, then value one is considered in the place by default. Thus, it returns the
sequence that begins from 1. Similarly, if “increment” is not specified, the increment’s default value is also
considered as one. It means each item of the sequence is greater than its previous item by 1. For example,
#generate a sequence by specifying
#starting, maximum ending and increment values
for i in range(3,18,6):
print("range(3,18,6):",i)
41
#starting and maximum values
for i in range(5,12):
print("range(5,12):",i)
The range() function is very often used in combination with another built-in function len(). It returns the
number of items or elements present in an object, such as a list and a string. To know the total count of
elements in a list, just mention that list’s name within the parenthesis. For example,
#initialise a list
grocery = ["rice", "flour", "lentils", "tea", "sugar", "spices",
"milk", "oil", "nuts", "snacks"]
#initialise a string
name = "Kabir"
The range() and the len() are very helpful to iterate exactly the same number of times over a list as the
count of all the elements using a for loop. For example,
#initialise a list
alphabet = ["a ", "b ", "c", "d", "e", "f", "g"]
42
for i in range(len(alphabet)):
print(alphabet[i])
Break, continue and pass statements are used to alter the flow of execution of loops. These statements
are very often implanted with nested loops, which are described in the next section. A break statement is
used to jump out of the loop. This means that once a break statement is executed in a loop, the loop’s
further execution is ceased. It can stop both for and while loops. It is generally used in situations when a
loop’s execution is required to be stopped due to external conditions. The action of break statement is
depicted in the following example,
43
break
print("For loop execution no.", i)
print("The for loop has been broken")
Output:
Unlike a break statement, a continue statement is used to skip the current iteration of a loop. In other
words, when a continue statement is executed within the loop, then the rest of the statements after the
break statement inside the loop in the current iteration are not executed or simply skipped. Instead, it
brings the loop’s control at the beginning, i.e. conditional expression of the loop. The following flowchart
depicts this.
44
The following example demonstrates the usage of a continue statement.
45
Output:
1 is an odd number
3 is an odd number
5 is an odd number
7 is an odd number
9 is an odd number
2 is an even number
4 is an even number
6 is an even number
8 is an even number
10 is an even number
Unlike a break and a continue statement, a pass statement does nothing in the program. It is a null
statement in Python, which means nothing transpires due to this statement’s execution like comments.
The only difference between pass statements and comments is that Python interpreters ignore comments
altogether but does not ignore pass statements. If it does nothing, then obviously, a question arises: What
is its purpose in Python programming? The answer is straightforward; it is commonly used as a
placeholder for those places that cannot have an empty body, such as the bodies of functions or loops.
If they are kept empty, the interpreter gives an error. The pass statement is used to avoid errors.
Naturally, the second question arises, why would somebody define a function or loop in the first place if
it does nothing? The answer is that the implementation of such functions and loops is scheduled in the
future because they are either not needed or ready. Therefore, instead of keeping them empty and getting
an unnecessary error, the pass statement can avoid an error. Moreover, it does not affect the program’s
output as well. The following example demonstrates the usage of this statement.
for i in range(100):
pass
D. Nested loops
A Nested loop is a loop inside another loop. Python also supports nested loops. For example,
In this, the completed execution of the inner loop follows every iteration of the outer loop. The following
flowchart diagram can be helpful to understand this.
46
The following example shows the usage of the nested loop.
#list down all prime numbers between 2 and 250
#create a list store prime numbers
Prime_list = []
for i in range(2,251):
p = True; j=2
or
47
# create a list to save prime numbers
Prime_list = []
#set up a loop
for Number in range (1, 251):
#create a count variable and assign zero it
count = 0
for i in range(2, (Number//2 + 1)):
#break if the number is even or non-prime odd
if(Number % i == 0):
count = count + 1
break
#if "count" remains zero by the end of the inner loop,
#then it means the corresponding number is prime
if (count == 0):
Prime_list.append(Number)
print(Prime_list)
Output:
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61,
67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137,
139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211,
223, 227, 229, 233, 239, 241]
1.8 Functions
Functions are a beneficial concept in programming because it breaks down a program into many small
parts. These smaller parts organise long programs in a manageable way. Functions also increase the
readability and reusability of codes. It helps programmers to avoid the repetition of codes in programs.
1.8.1 Function Definitions and Function Calls
A function is nothing but a block of code or a group of statements that performs a specified task. Once a
function is defined in a program, it can be executed as many times as required by calling it at any point
in time. A function can be called by just mentioning its name. Another critical thing about functions, they
do not execute unless they are called.
Defining functions:
The syntax for a function is as follows.
def functionName(parameters):
Statements
return [expression]
The following points are required to define a function in a Python program.
1. The keyword def is always followed by the name of a function.
2. The name of a function is always followed by a pair of open and close parentheses or round
brackets ( ).
3. Arguments or parameters are placed inside the parenthesis and speared commas. They are used
to pass values to the function, and they are not compulsory.
48
4. After the parenthesis pair, a colon : is placed to mark that the function header ends.
5. The function’s statements start after the colon and appropriate indent, i.e. usually four spaces.
6. The keyword return precedes the return value in a function. However, it is not compulsory that
every function must return a value.
Calling a Function
After defining a function, it can be called from another function or program. To do that, it is required to
type the name of the function with appropriate parameters or no parameter For example,
#define a simple function
def simpleFunc():
print("This is a very simple example of a function.")
The following example shows a function with arguments and returns a value.
#define a function
def add(a, b):
return a+b
49
#create a lambda function
cube = lambda x: x*x*x
Lambda functions are often used in the combination of higher-order functions to deal with
arguments/parameter pass. For example,
#create a function to calculate
#Total surface area of a box
def tsa_function(x, y, z):
return 2*x*y*z
1. Local Variables: Those variables, which are defined inside functions, are called local variables.
2. Global Variables: Those variables that are defined outside are called global variables.
The scope of a local variable is minimal and limited within the body of a function where it is declared.
Outside the function, such variables are not visible and cannot be accessed. On the other hand, the global
variable can be accessed from anywhere in the program to all functions. Besides this, the difference in a
lifetime also exists between these two. The term lifetime in the context of variables means the total time
during which a variable exists in the memory. A local variable’s lifetime inside the function is equivalent
to the time needed to execute that function. The variable is destroyed once the execution of that program
50
is completed. Therefore, such functions do not retain the value of a variable from previous calls. The
following program demonstrates this.
Output:
51
Lesson 2: Python Language Overview - 2
In the continuation of the last lesson, this lesson also sheds some light on the different programming
concepts in Python. This chapter deals with the concept of classes, modules and file input and output.
2.1 Classes
Classes and objects are fundamental concepts of all object-oriented programming languages. They both
are related to each other: a class is a just blueprint, plan, or template for creating objects. Put it another
way; an object is an instance of a class with its variables and functions. The following analogy is apt for
increasing the understanding of this concept.
There are overwhelming numbers of many similar objects available in day-to-day life. A bicycle is just one
such example. In object-oriented programming terminology, it is nothing but an object or an instance of
the class bicycle. In general, all the bicycles have some states and behaviours in common. States such as
two wheels, gear mechanism, one seat, etc. Behaviours include break, gear change, movement, etc.
Nevertheless, these features of each bicycle are independent and a little different from one another.
Bicycle manufacturers leverage the fact that bicycles share lots of commonalities. As a result, they
manufacture many bicycles from a single blueprint instead of having individual blueprints for each bicycle.
The same idea has been used in object-oriented programming; many objects that share common traits
are created by a single blueprint, i.e. a class. It is exactly like bicycles. Concisely, a class is a blueprint or
template that defines methods and variables for all objects that share commonalities in terms of state
and behaviours.
class class_name:
#class_variables
After defining a class, the next step is to create an instance of it, i.e. an object. To do that, the class’s name
is used, and arguments are passed if there are any.
object_name = class_name(arg0, arg1, ..., argN)
The following example demonstrates how to create a simple class and an object.
52
#create a class
class student:
"This is a student class"
roll_no = 27
def result(self):
print('Pass')
In the above example, the definition of the result() method contains a default argument, i.e. self.
Nevertheless, no argument has been passed to the result() method when it has been called. Because
whenever an object calls a method, it passes itself as a first argument to the method. It means
[Link]() is equivalent to this [Link](Kabir). For that reason, as a convention, the self is used.
It is a non-binding word; it can be replaced with another word. However, it is highly recommended to use
this word only.
53
def displaystudent(self):
print ("Name:", [Link], ", Age:", [Link])
pupil_1.displaystudent()
pupil_2.displaystudent()
pupil_3.displaystudent()
print ("Total student:", student.roll_no)
print("Students records: ", [Link])
Output:
Name: Adam , Age: 14
Name: David , Age: 15
Name: Simran , Age: 13
Total student: 3
Students records: {1: ['Adam', 14], 2: ['David', 15], 3: ['Simran', 13]}
2.2 Modules
Modules are different files that contain codes such as variables, statements and definitions of functions
and classes. In other programming languages, it is also called a code library. It enables programmers to
logically arrange and organise Python codes, which have been developed for a particular project.
Subsequently, it makes Python code highly readable and fast to understand. Moreover, creating a module
is simple. After typing Python codes in a text file, save that file with an appropriate name and “.py”
extension. For example, save the following code with the name “[Link]” in computer folder.
#this Python file will use
#as a module in other files
def add(x, y):
sum = x + y
return sum
In the file mentioned above, a function has been defined but not called. It means, if the above file is
executed, nothing will happen. However, this function can be called and executed from a different Python
file. Therefore, the file mentioned above is required to be imported as a module in another file where the
add() function is needed to be called.
54
2.2.1 Import statement
A statement can be used to import a file into another program. In which the name of the file is followed
by keyword import. Moreover, multiple modules or files can be imported with one statement’s help by
mentioning their names after the keyword. The general syntax for it is mentioned as follows.
import module1, Module2, …, ModuleN
For example,
#Import the file
import ExampleModule
As mentioned above, the module rename is implemented in the below given example.
#Import the module and rename it
import ExampleModule as ExModule
55
The following module contains different functions. Each of these functions is capable of calculating
different physical entities.
function_detail = ["speed(distance, time)", "acceleration(speed, time)",
"momentum(speed, mass)", "force(acceleration, mass)"]
The name of this module is “[Link]”. Suppose a program requires calculating momentum only.
In this case, importing the entire module is meaningless. Therefore the from keyword is helpful to import
specific parts of the module. For example,
#import function detail and the momentum function
# from CalcModule
from CalcModule import function_detail, momentum
#create variables
speed = 72
mass = 1500
56
2.2.4 From ... Import * Statement
It is also possible to import an entire module from the following statement.
from ModuleName import *
In the following example, the entire module of [Link] is imported into the program.
#import the whole of [Link] module
from CalcModule import *
#create variables
time = 12
distance = 360
mass = 1200
a = acceleration(V, time)
print("acceleration =", a)
L = momentum(mass, V)
print("momentum =", L)
F = force(a, mass)
print("force =", F)
Output:
['speed(distance, time)', 'acceleration(speed, time)', 'momentum(mass,
speed)', 'force(mass, acceleration)']
speed = 30.0
acceleration = 2.5
momentum = 36000.0
force = 3000.0
57
There are various good standard built-in modules in Python. Built-in modules are always present in
Python. They come in very handy in a variety of situations. For example, the math module provides a
variety of mathematical functions. The dir() function can be used to know all of that. For example,
import math
dir(math)
Output:
['__doc__', '__loader__', '__name__', '__package__', '__spec__',
'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil',
'comb', 'copysign', 'cos', 'cosh', 'degrees', 'dist', 'e', 'erf',
'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp',
'fsum', 'gamma', 'gcd', 'hypot', 'inf', 'isclose', 'isfinite', 'isinf',
'isnan', 'isqrt', 'lcm', 'ldexp', 'lgamma', 'log', 'log10', 'log1p',
'log2', 'modf', 'nan', 'nextafter','perm', 'pi', 'pow', 'prod',
'radians', 'remainder', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'tau',
'trunc', 'ulp']
The filename argument is a string used to specify the file’s name, required to be accessed for reading,
writing or other operations. On the other hand, the mode argument informs the function about the
purpose of file opening, whether to read, write, append, etc. Besides, whether the file is handled as a text
or binary file can be specified. These different modes can be selected with the help of a text string, as
mentioned below.
58
Mode
Descriptions
argument
Read: This mode is the default. It opens the file for reading. It returns an error if
“r”
the file does not exist. It places the file pointer at the beginning of the file.
Text: This specifies that the particular file must be handled as a text file. By default,
“t”
files are handled as text.
“b” Binary: This specifies that the particular file must be handled as binary.
Read Binary: It opens a file to read in binary format. Then, it places the file pointer
“rb”
at the beginning of the file.
Read and write: It opens a file for both reads and writes. Then, it places the file
“r+”
pointer at the beginning of the file.
Read and write – binary: It opens a file for both reads and writes in binary format.
“rb+”
It places the file pointer at the beginning of the file.
Write: It opens a file for writing only. It overwrites if the file exists. It creates a new
“w”
file if the file does not exist.
Write binary: It opens a file for writing only in binary format. It overwrites if the
“wb”
file exists. It creates a new file if the file does not exist.
Write and read: It opens a file for both reads and writes. It overwrites if the file
“w+”
exists. It creates a new file if the file does not exist.
Read and write - binary: It opens a file for both reads and writes in binary format.
“wb+”
It places the file pointer at the beginning of the file.
Append: It opens a file to append. It places the file pointer at the end of the file. It
“a”
creates a new file if the file does not exist.
Append binary: It opens a file to append in binary format. It places the file pointer
“ab”
at the end of the file. It creates a new file if the file does not exist.
Append Read: It opens a file to append and write. It places the file pointer at the
“a+”
end of the file. It creates a new file if the file does not
Append Read binary: It opens a file to append and write in binary format. It places
“ab+”
the file pointer at the end of the file. It creates a new file if the file does not
“x” Create: It creates a specific file. Then, it returns an error if the file exists.
After opening a file, any operation of reading, writing, etc., can be done. Eventually, the open file object
is also required to be closed. Another built-in function is used to do that called close(). All the unwritten
data is destroyed once this function is executed. Therefore, it is always a good practice to run this function
once the task has been done. The general syntax of this is mentioned below.
file_object.close()
59
#first, make sure that "[Link]" must be
#available in the folder
Output:
Hello world!
The complete path is required when the file is located somewhere else on the computer, as shown below.
Output:
Name: Kabir
Age: 12
Std: V
Sometimes only, a specific part of a file is required to read. That can be specified in the read function. For
example,
60
#first, make sure that "Roll_23.txt" must be
#available in the specified folder
Output:
Name: Kabir
When a text file is located at a particular location on the computer or a new file is needed to be created
at a specific file location. The complete path of the file goes as an argument of the open() function. For
example,
#create file object to write the file
txt_file = open("[Link]", "w") #a new file is created if "Roll_2
[Link]" does not exist
61
2.3.4 File Append
Instead of writing text in a new file, very often some new text is needed to be added to an existing file.
This is called append. A built-in function append() is used to do this. Like a write(), it writes text in a file,
but unlike write(), it does not overwrite the file’s existing text. A new file is created only if the specified
file does not exist on the computer. For example,
The following is the screenshot of a text file, which a Python program will append.
After the execution of the above program, the text file is appended, as shown below.
In similar ways, the different combinations of reading, writing and append can be used to handle files on
the computer.
62
2.3.5 File Delete
After creating a computer file, one should also know how to delete the file using Python. This section
describes the way by which a file or a folder on the computer can be deleted. A built-in library or module
is needed to import into the program to accomplish this goal. The module name is “os”. The below-given
line of code is used to import the module.
import os
After importing the os module, this module’s remove() function is used to delete files. The string of a file
name is passed as an argument to this function to specify the file. For example,
#import the os module
import os
The remove() function returns an error if a specified file does not exist. Therefore, it is always
recommended to check the file’s existence before executing the remove() function to avoid this error. It
can be checked with the help of the following lines of codes.
#import the os module
import os
Like files, folders can be deleted on the computer. Another function, rmdir(), is used to do this. For
example,
#import the os module
import os
63