0% found this document useful (0 votes)
2 views66 pages

Python Overview

Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views66 pages

Python Overview

Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

2022

Python Overview

PODAR INNOVATION LAB


PODAR INNOVATION LAB
Contents
Lesson 1: Python Language Overview - 1 .................................................................................................. 1
1.1 Environment setup .............................................................................................................................................................. 1
1.1.1 Download ...................................................................................................................................................................... 1

1.1.2 Install ............................................................................................................................................................................... 1

1.1.3 Get started with Python IDLE ................................................................................................................................. 3

1.2 Basic Syntax ........................................................................................................................................................................... 8


1.2.1 Statement Structure .................................................................................................................................................. 8

1.2.2 Indentation.................................................................................................................................................................... 9

1.2.3 Comments ...................................................................................................................................................................10

1.3 Literals ....................................................................................................................................................................................11


1.4 Variables................................................................................................................................................................................12
1.4.1 Variable Naming Convention ..............................................................................................................................13

1.4.2 Create and Assign Value to Variable ................................................................................................................13

1.5 Operators ..............................................................................................................................................................................14


1.5.1 Arithmetic operators ...............................................................................................................................................15

1.5.2 Assignment Operators ...........................................................................................................................................15

1.5.3 Comparison Operators ...........................................................................................................................................17

1.5.4 Logical Operators .....................................................................................................................................................18

1.5.5 Identity operators .....................................................................................................................................................18

1.5.6 Membership operators ..........................................................................................................................................19

1.6 Data Structures ...................................................................................................................................................................20


1.6.1 Lists ................................................................................................................................................................................20

1.6.2 Tuples ............................................................................................................................................................................24

1.6.3 Dictionaries .................................................................................................................................................................26

1.6.4 Sets .................................................................................................................................................................................28

1.7 Control Structures .............................................................................................................................................................33


1.7.1 Decision Making .......................................................................................................................................................33

1.7.2 Loops .............................................................................................................................................................................38

1.8 Functions...............................................................................................................................................................................48
1.8.1 Function Definitions and Function Calls ..........................................................................................................48

1.8.2 Lambda function .......................................................................................................................................................49

1.8.3 Scope of Variable .....................................................................................................................................................50


Lesson 2: Python Language Overview - 2 ................................................................................................ 52
2.1 Classes ...................................................................................................................................................................................52
2.1.1 Creating Class ............................................................................................................................................................52
1|Page

2.1.2 Special function names ..........................................................................................................................................53

2.2 Modules ................................................................................................................................................................................54


2.2.1 Import statement......................................................................................................................................................55

2.2.2 Renaming a Module ................................................................................................................................................55

2.2.3 From ... Import Statement .....................................................................................................................................55

2.2.4 From ... Import * Statement ..................................................................................................................................57

2.2.5 dir( ) Function .............................................................................................................................................................57

2.3 File Handling .......................................................................................................................................................................58


2.3.1 Files Opening and Closing ....................................................................................................................................58

2.3.2 File Read .......................................................................................................................................................................59

2.3.3 File Write/Create .......................................................................................................................................................61

2.3.4 File Append .................................................................................................................................................................62

2.3.5 File Delete ....................................................................................................................................................................63


Lesson 1: Python Language Overview - 1
Python is a high level, general-purpose, interactive, interpreter based language. It is prevalent because of
its simplicity. It supports various kinds of programming paradigms such as object-oriented, imperative,
functional and procedure-oriented styles. Furthermore, it is a cross-platform programming language
because the interpreter is available for numerous Operating Systems such as Windows, Mac, Linux, UNIX
and many more. This lesson is an overview of the Python programming language, which is already
described in computer studies.

1.1 Environment setup


This course explores the application of Python. For that reason, the latest version of Python 3 is needed
to be installed in the system. The procedure for that is mentioned in the below subsections.

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.

2. Right-click on it spontaneously, a context menu appears on the screen, as displayed below.

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.

5. Instantaneously, the following dialogue box appears on the screen.

6. Make sure that both the checkboxes at the bottom of the dialogue box are checked.

7. Then, click the Install Now option.

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.

1.1.3 Get started with Python IDLE

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.

Typing a script on IDLE:


The following description shows how to use Python IDLE for writing codes.

1. To open Python IDLE, click on the icon of Python IDLE.

2. Promptly after that, the following window appears on the screen.

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.

4. Immediately after that, the following window opens up on the screen.

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.

Open and edit an existing script:


In several instances, it becomes necessary to edit an existing file of a Python script. The procedure for that
is mentioned below in a stepwise manner.
1. First, open Python IDLE, and then on the menu bar, select File >> Open as shown below.

Instead of this, use keyboard shortcuts Ctrl + o.


2. The following dialogue box appears on the screen. Using it, navigate to the file location and select
the desired file box. Then, click the Open button.

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.

Alternatively, use keys Ctrl + s.

5. Promptly, all the changes are saved in the file. After this, the script can be executed.

1.2 Basic Syntax


The syntax of a programming language describes the structure of the language. Simply put, it is a ruleset
to determine whether a program is correctly formed. This is based on the combination or arrangement of
strings of characters of all the program constituents. Compared to several other programming languages,
Python’s syntax is straightforward to read and understand for both beginners and experts alike.
1.2.1 Statement Structure
Python statements: Each statement or instruction of a Python program is terminated with a token of
newline characters. Generally, a statement occupies a physical line. For example,
print ("1st Statement")
print ("2nd Statement")
print ("3rd Statement")
This example has three statements in three separate lines. Bear in mind that Python ignores a line with
only space or tab, and it does not execute it.

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

print(b, ", ", o,", ", d, ", ", h)


print(p_float, ", " , e_float)
print(z, ", Imaginary Part:", [Link], ", Real Part:", [Link])
Output:
111 , 111 , 111 , 111
62.43 , 6.023e+23
(2+6.62j) , Imaginary Part: 6.62 , Real Part: 2.0
From the output, it is clear that all integers are printed as decimal only. Bear in mind, the value of
j is √−1.
2. String and character literals: A string literal is a sequence of characters enclosed within single
quotes, double quotes or triple quotes. In the case of a character literal, a single character is held
within single or double-quotes. For example,
#String literal
s = "This is the string."

11
#Character literal
c = "a"

#Multiple strings literal


multi-line_string = """This is a multi-line string
literal, which is
spanning over more
then one line."""

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,

x = True # Boolean type


print(x)

x= 568 # Integer type


print(x)

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'

#Invalid variable names


1stname = 'Kabir'
first-name = 'Kabir'
first name = 'Kabir'

1.4.2 Create and Assign Value to Variable


From previous examples, it is clear that a variable holds a value. Unlike most popular programming
languages, Python does not require any explicit declaration of a variable before assigning a value to it.
Declaration of a variable takes place automatically when a value is assigned to the variable. Thus, all one
needs to create a variable in Python, just provide a variable name and assign a value to it. The sign of
equality (=) is used to assign a value to a variable. For example,

#Declaration of different types of variables


name = "Raju" # A string assignment
age = 12 # A integer assignment
height = 58.7 # A float assignment

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.

/ The division operator is used to divide a left operand by a right operand—


for instance, a/b.
% It is the modulus operator, which is used to get the remainder of the two
operands. So, for example, 3%2 returns 1 because it is a remainder.
// If it is used for division, it rounds down the division’s result to the nearest
whole number. For example, 3//2 results 1 instead of 1.5
** It is the exponential operator; it makes the first operand base and second
operand as power. For example, 2**3 returns 8.
The following example shows how these operators work.
p = 9
q = 2

print('p + q =', p+q) #addition


print('p - q =', p-q) #subtraction
print('p * q =', p*q) #multiplication
print('p / q =', p/q) #division
print('p % q =', p%q) #modulus
print('p // q =', p//q) #floor division
print('p ** q =', p**q) #exponent
Output:
p + q = 11
p - q = 7
p * q = 18
p / q = 4.5
p % q = 1
p // q = 4
p ** q = 81

1.5.2 Assignment Operators


The assignment operators are used to assign a value to a variable. For example, x = 2, here the equal is
an assignment operator, and 2 is being assigned to the x. There are many assignment operators available
in Python. Besides the equal operator, all others are compound operators that assign a value and perform
an arithmetical operation. The following operators are known as Python assignment operators.

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

The following example shows how these operators work.


x = 15; print("x =", x)

x += 2; print("x += 2, then x =", x)


x -= 2; print("x -= 2, then x =", x)
x *= 2; print("x *= 2, then x =", x)
x /= 2; print("x /= 2, then x =", x)
x %= 2; print("x %= 2, then x =", x)

y=11; print("y =", y)


y //= 2; print("y //= 2, then x =", y)
y **= 2; print("y **= 2, then x =", y)
Output:
x = 15
x += 2, then x = 17
x -= 2, then x = 15
x *= 2, then x = 30
x /= 2, then x = 15.0
x %= 2, then x = 1.0
y = 11
y //= 2, then x = 5
y **= 2, then x = 25

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

The following example demonstrates how these operators work.


a = 5; print("a =", a)
b = 3; print("b =", b)

#To check whether a is greater than b


print('a > b is', a > b)

#To check whether a is less than b


print('a < b is', a < b)

#To check whether a is greater than or equal to b


print('a >= b is', a >= b)

#To check whether a is less or equal to than b


print('a <= b is', a <= b)

#To check whether a is equal to b


print('a == b is', a == b)

#To check whether a is not equal to b


print('a != b is', a != b)
Output:
a = 5
b = 3
a > b is True
a < b is False

17
a >= b is True
a <= b is False
a == b is False
a != b is True

1.5.4 Logical Operators


Logical operators are used to combine conditional statements. There are various logical operators
available in Python as follows.
Operator Description Example
(10==20) and (20==33) = false
True if both operands
and (50>35) and (60<75) = true
are true
(23<23) and (50>45) = false
True if either one out (10==20) or (20>=33) = false
or of two operands is (10<20) or (20 != 33) = true
true (45>=75) or (20<33) = true
not(20=20) = false
True if an operand is
not not(10>20) = true
not true
not(10<20) = true
With the help of the following truth table, logical operators’ actions can be understood very easily.
A B A and B A or B not A
False False False False True
False True False True True
True False False True False
True True True True False
The following example demonstrates how these operators work.
A = True
B = False

print('A and B is', A and B)


print('A or B is', A or B)
print('not A is', not A)
Output:
A and B is False
A or B is True
not A is False

1.5.5 Identity operators


There are two identity operators in Python. They are used to determine whether two values of two
variables are located at the exact same memory location. They are used because, very often, two variables
with equal values are not always identical. The identity operators are mentioned below.
Operator Description Example
is It returns true when operands are identical A is B
is not It returns true when operands are not identical A is not B

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)

#id() function returns a unique identity of an object.


print("The unique ID of A:", id(A))
print("The unique ID of B:", id(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

1.5.6 Membership operators


There are two membership operators in Python. These operators are used to check whether a variable or
value is present in a sequence or not. It can be anything such as string, list, tuple, set and dictionary. The
membership operators are mentioned below.

Operator Description Example


It returns true when a value or variable
in 3 in sequence
exists in the sequence
It returns true when value or variable
not in 3 not in sequence
does not exist in the sequence

The following example demonstrates how these operators work.


fruits = ["apple", "avocado", "kiwi", "mango", "orange"]
print("mango" in fruits)
print ("banana" not in fruits)
Output:
True
True

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)

#create a list with data


mylist_2 = [12, True, 5, 2 + 6.62j, 'Newton', 'g', 9.8]
print(mylist_2)

#Create a list with another list


fruit_List = ["apple", "mango", "Orange"]
mylist_3 = [3, 2, "colour", "Fruits", ["red", "yellow", "orange"],
fruit_List]
print(mylist_3)

Output:
[]

20
[12, True, 5, (2+6.62j), 'Newton', 'g', 9.8]
[3, 2, 'colour', 'Fruits', ['red', 'yellow', 'orange'], ['apple',
'mango', 'Orange']]

Accessing List Elements


Each element in a list has an index number depending upon its position in the list. The first element of
every list starts with index 0; the second element has index 1; the third element has index 2, so on. Each
index must be an integer. An element or part of a list can be accessed using these indexes. For example,
TshirtSize = ["3XS","2XS", "XS","S", "M", "L", "XL", " 2XL", "3XL"]

#Access first element


print(TshirtSize[0])

#Access fourth element


print(TshirtSize[3])

#Access first three elements


print(TshirtSize[0:3])

#Access all element from 4th element to last


print(TshirtSize[3:])

#Access last element


print(TshirtSize[-1])

#Access last two elements


print(TshirtSize[-2:])

#Access 1st to 4th last elements


print(TshirtSize[: -3])

#Access all elements


print(TshirtSize[:])
Output:
3XS
S
['3XS', '2XS', 'XS']
['S', 'M', 'L', 'XL', ' 2XL', '3XL']
3XL
[' 2XL', '3XL']
['3XS', '2XS', 'XS', 'S', 'M', 'L']
['3XS', '2XS', 'XS', 'S', 'M', 'L', 'XL', ' 2XL', '3XL']

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

3XS 2XS XS S M L XL 2XL 3XL


-6 -8 -7 -6 -5 -4 -3 -2 -1

[-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)

# Goa is not a city but a state


city[4]='Pune' # Replace Goa with Pune
print(city)

# The Bangalore and Calcutta have renamed


city[1:3] = ["Bengaluru", "Kolkata "]
print(city)
Output:
['Mumbai', 'Banglore', 'Calcutta', 'Hyderabad', 'Goa', 'Chennai']
['Mumbai', 'Banglore', 'Calcutta', 'Hyderabad', 'Pune', 'Chennai']
['Mumbai', 'Bengaluru', 'Kolkata ', 'Hyderabad', 'Pune', 'Chennai']

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)

#add Ahmadabad in the list


[Link]('Ahmadabad')
print(city)

#Add more than one cities in the list


[Link](['Surat', 'Jaipur', 'Lucknow', 'Kanpur', 'Nagpur', 'Indore'])
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']

#combine the lists


colour = colour + sec_colour
print(colour)

#create a list with two element


grey = ['black', 'white']

#Repeat black and white thrice in the list


grey = grey *3
print(grey)
Output:
['red', 'green', 'blue', 'Yellow', 'magenta', 'cyan']
['black', 'white', 'black', 'white', 'black', 'white']

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']

#delete an element of the list


del grains[0]
print(grains)

#delete last three elements


del grains[-3:]
print(grains)

#delete the entire list


del grains
print(grains) #shows the error grains' is not defined

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 snow leopard from the list


[Link]("snow leopard")
print(animals)

#remove an item from the list


print([Link]())
print(animals)

#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)

#create a tuple with various data


Sherlock_Holmes = ("Arthur Conan", "Doyle", 1887, "English", "novels",
"Detective fiction")
print(Sherlock_Holmes)

#create a tuple that contains a list and another tuple


colour = ( "white", ("red", "green", "blue"), ["Cyan", "Magenta",
"Black", "Yellow"])
print(colour)
Output:
()
('Arthur Conan', 'Doyle', 1887, 'English', 'novels', 'Detective fiction')
('white', ('red', 'green', 'blue'), ['Cyan', 'Magenta', 'Black', 'Yellow'])

Accessing Tuple Elements


Analogous to list, each element of a tuple can be accessed using index number and square bracket. A part
of a tuple can be sliced using slicing operators. For example,
# create a tuple
tuple_1 = ('i', 'm', 'm', 'u', 't', 'a', 'b', 'l', 'e')
print(tuple_1)

print(tuple_1[5])
print(tuple_1[2:])

# create a tuple which includes a list and another tuple


tuple_2 = ("Even", [2,4,6,8], "Odd", (1,3,5,7,9))

# use nested index to select elements


print(tuple_2[1][2])
print(tuple_2[3][2])
Output:
('i', 'm', 'm', 'u', 't', 'a', 'b', 'l', 'e')
a
('m', 'u', 't', 'a', 'b', 'l', 'e')
6
5

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)

# Change any mutable element of the tuple


colour[1][6] = "violet"
print(colour)

#No try to change an immutable element of the tuple


colour[1] = "SevenColour"

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)

# print the height of student


print(student["height"])

# print the name of student


print(student["name"])
Output:

26
{'name': 'Kabir Malik', 'std': 8, 'height': 66.7, 'Gender': 'M'}
66.7
Kabir Malik

Adding and Updating Dictionaries


Dictionaries are also mutable data structures like lists. The values of any dictionary can be changed at any
point in time. Furthermore, a new value can be added. For example,
#create dictionary
Food_Dict = {"Vegetable":"broccoli", "Fruit":"grapes",
"Grain":"wheat", "Protine_Food":"tofu" }
print ("Original Food_Dict ", Food_Dict)

#add one more value in the dictionary


Food_Dict["Dairy"] = "cheese"

#add one more value in the dictionary


Food_Dict["oil"] = "olive oil"

#Update an existing value


Food_Dict["Vegetable"] = "spinach"

#print the entire dictionary


print("Food_Dict after addition and update: ", Food_Dict)
Output:
Original Food_Dict {'Vegetable': 'broccoli', 'Fruit': 'grapes',
'Grain': 'wheat', 'Protine_Food': 'tofu'}
Food_Dict after addition and update: {'Vegetable': 'spinach',
'Fruit': 'grapes', 'Grain': 'wheat', 'Protine_Food': 'tofu', 'Dairy':
'cheese', 'oil': 'olive oil'}
A specific key-value pair of a dictionary or an entire dictionary is deleted with the help of keyword del. In
order to do that, the name of a dictionary and key of value or only a dictionary is preceded by the keyword
del. For example,
#create dictionary
Food_Dict = {"Vegetable":"broccoli", "Fruit":"grapes", "Grain":"wheat"
, "Dairy":"cheese", "oil":"olive oil" }
print ("Original Food_Dict ", Food_Dict)

#delete one value from the dictionary


del Food_Dict["Vegetable"]
print("After deleting one value", Food_Dict)

#delete one value from the dictionary


del Food_Dict["Grain"]
print("After deleting one more value", Food_Dict)

27
#delete an entire dictionary
del Food_Dict

#print will give an error


print(Food_Dict)

Output:
Original Food_Dict{'Vegetable': 'broccoli', 'Fruit': 'grapes',
'Grain': 'wheat', 'Dairy': 'cheese', 'oil': 'olive oil'}

After deleting one value {'Fruit': 'grapes', 'Grain': 'wheat',


'Dairy': 'cheese', 'oil': 'olive oil'}

After deleting one more value {'Fruit': 'grapes', 'Dairy': 'cheese',


'oil': 'olive oil'}

Traceback (most recent call last):


File "<stdin>", line 1, in <module>
NameError: name 'Food_Dict' is not defined

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)

#create a non empty set using in-built set function


days = set(["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"])
print(days)

#create a non empty set using curly braces


First_Quarter = {"Jan", "Feb", "Mar"}
print(First_Quater)

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.

Accessing Set Elements


As explained, an individual element of a set cannot be accessed since no index number is attached to it.
However, all the elements of a set can be accessed together, as demonstrated in the previous example. A
for loop is the workaround to obtain each element of a set separately. For example,
#create a non-empty set
vowel = {"a", "e", "i", "o", "u"}

#Access each element with the help of a loop


for i in vowel:
print(i)
Output:
o
u
e
i
a
Loops are discussed in detail in the subsection of the control structure, i.e. 1.7.2 Loops.

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)

#now add one item in the set


[Link]("y")
print("Updated alphabet set: ", alphabet)

#finally add several items in the set


[Link]("a", "b", "c", "d", "f", "g",

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)

#discard an element that is not present in the set


[Link]("Mon")
print(week)

#remove an element that is not present in the set


[Link]("Mon")
#it provides an error message
Output:
{'Wed', 'Mon', 'Thu', 'Sat', 'Fri', 'Tue', 'Sun'}
{'Wed', 'Mon', 'Thu', 'Sat', 'Fri', 'Tue'}
{'Wed', 'Thu', 'Sat', 'Fri', 'Tue'}
{'Wed', 'Thu', 'Sat', 'Fri', 'Tue'}
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'Mon'

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)

#Create a set of numbers greater than 5


B = {6, 7, 8, 9, 10}
print("Set of Numbers > 5: B = ", B)

#Perform union operation on both the set


AUB = A | B #instead, AUB = [Link](B) can be used
print("AUB = ", AUB)
Output:
Set of Even Numbers: A = {2, 4, 6, 8, 10}

Set of Numbers > 5: B = {6, 7, 8, 9, 10}

AUB = {2, 4, 6, 7, 8, 9, 10}

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)

#create a set of numbers greater than 5


B = {6, 7, 8, 9, 10}
print("Set of Numbers > 5: B = ", B)

#perform intersection operation on both the set


AB_intersect = A & B
#instead, AB intersect = [Link](B) can be used

print("A∩B = ", AB_intersect)


Output:
Set of Even Numbers: A = {2, 4, 6, 8, 10}
Set of Numbers > 5: B = {6, 7, 8, 9, 10}
A∩B = {8, 10, 6}

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)

#Create a set of numbers greater than 5


B = {6, 7, 8, 9, 10}
print("Set of Numbers > 5: B = ", B)

#perform difference operation on both the set


AB_diff = A - B
#instead, AB_diff = [Link](B) can be used

print("difference = ", AB_diff)

Output:

Set of Even Numbers: A = {2, 4, 6, 8, 10}


Set of Numbers > 5: B = {6, 7, 8, 9, 10}
difference = {2, 4}

1.7 Control Structures


The data structures are different ways in which information can be organised. On the other hand, control
structures contain algorithms and specify the control flow of a program. In other words, control structures
set the order in which individual instruction or statement of a program is executed. Pythons support all
traditional control structures that are discussed below.

1.7.1 Decision Making


In programming, decision-making happens through conditional statements. These statements execute
only when certain boolean conditions are met. These conditions are specified in programs by
programmers. These conditions are generally small statements in which variables are compared against
other variables or values. These conditions are created by using different combinations of comparison
and logical operators. For example,

▪ 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

#test the value of the variable


if age>18: #condition
#the following message will print only if the condition is true.
print("You are eligible to vote in the public election.")
Output:
You are eligible to vote in the public election.

B. if ... else statements


This type of conditional statement gives a little greater control over the execution flow of programs. Here,
statements are executed if a specific condition is true. Otherwise, another set of statements are executed
that are present after the else keyword. The syntax for an if ...else statement is as follows.
if (condition):

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.

The following statements show a small application of this conditional statement.


#create and assign a value to a variable
age = 17
#test the value of the variable
if age>=18:
print("Your age is ", age)
print("It means you are eligible to vote in the public election.")
else:
print("Since you are below 18.")
print("You are not eligible for voting")
Output:
Since you are below 18
You are not eligible for voting

C. if … elif … else statements


This is an advanced conditional statement in which more than one condition can be tested in order to
execute appropriate block statements. This is very helpful to make correct decisions by testing several
conditions. Each new condition is placed after the elif keyword. The syntax for an if...elif...statement is
as follows.
if (condition)the :
# this block statements execute
# only if the above condition is true
elif (condition):
#these block statements execute
#only if the previous condition is true

35
.
.
.
else:
#this block statement execute
#only if all above conditions are false

The following flowchart explains the execution flow of statements in an if...elif...statement.

The following statements show a small application of this conditional statement.


#create a variable and assign a value
x = 12

#create a if elif else statement


if (x < 0):
print("It is a negative number.")
elif (x>0):
print("It is a positive number.")
else:
print("The number is zero")
Output:
It is a positive number.

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

#create another variable and assign value


nationality = "Indian"

#Test both the value in nested if value


if (nationality == "Indian"):
if(age >=18):
print("You are ", nationality, " and ", age)
print("So, you are eligible to vote in the election")
else:
print("You are only ", age)

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

That means you are underage for voting

You can vote after 18

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

#use the while loop to print apology message


#ten times
while (counter < 10):
print("Sorry! I will not do it again")
counter = 1 + counter
Output:
Sorry! I will not do it again
Sorry! I will not do it again

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 syntax of this loop is mentioned below.

for iterative_variable in sequence:


#statements
In the first iteration, the iterative_variable is assigned the first item of the sequence, such as list, tuple,
etc. Subsequently, all the statements in the body of the loop are executed. In the second iteration,
iterative_variable is assigned the second item of the sequence. Consequently, the statements in the body
of the loop are executed. Likewise, in every iteration, each item of the sequence is assigned to the
iterative_variable. Moreover, the loop statements are also repeatedly executed until all the sequence
items are used up. Then, the loop gets broken, and the execution of other statements is resumed.

The program given below shows the application of a for loop in a program.

# create a list and assign values to it


grocery_list = ["rice", "flour", "lentils", ["tea", "sugar"],
"spices", "milk", "oil", "nuts", "cleaning products", "snacks"]

#create a variable and assign one to it


counter = 1

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)

#generate a sequence by specifying

41
#starting and maximum values
for i in range(5,12):
print("range(5,12):",i)

#generate a sequence by specifying


#specify only maximum ending value
for i in range(4):
print("range(4):",i)
Output:
range(3,18,6): 3
range(3,18,6): 9
range(3,18,6): 15
range(5,12): 5
range(5,12): 6
range(5,12): 7
range(5,12): 8
range(5,12): 9
range(5,12): 10
range(5,12): 11
range(4): 0
range(4): 1
range(4): 2
range(4): 3

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"]

#print the count of all the item in the above list


print("Total items in the grocery list:", len(grocery))

#initialise a string
name = "Kabir"

#print the total number of the characters in the name


print("Total character in the name:", len(name))

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"]

#iterate over the list with the help of len()

42
for i in range(len(alphabet)):
print(alphabet[i])

C. Break, continue and pass statement

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,

The following example demonstrates the usage of a break statement.

#create a for loop with break statement


for i in range(12): # range(12) = [0,1,2,3,4,5,6,7,8,9,10,11]
if i > 5:

43
break
print("For loop execution no.", i)
print("The for loop has been broken")

#create a while loop with a break statement


i = 0
while i < 12:
if i > 5:
break
print("While execution no.:", i)
i+=1
print("The while loop has been broken")

Output:

For loop execution no. 0


For loop execution no. 1
For loop execution no. 2
For loop execution no. 3
For loop execution no. 4
For loop execution no. 5
The for loop has been broken
While execution no.: 0
While execution no.: 1
While execution no.: 2
While execution no.: 3
While execution no.: 4
While execution no.: 5
The while loop has been broken

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.

#Create print all odd numbers between 1 and 10


#Using for loop and continue
for i in range(1,11):
if i%2 == 0:
continue
print (i, "is an odd number")

#Create print all even numbers between 1 and 10


#Using while loop and continue
j = 0
while (j < 10):
j +=1
if j % 2 ==1:
continue
print(j, "is an even number")

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,

● a for loop can be inside a while loop;


● a while loop can be inside a for loop;
● a while can be inside a while loop;
● or a for loop can be inside another for loop.

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

#the while loop starts after i reaches 4


while(j*j) <= i:
# the conditional statement sets p false
# if the number is either even or non-prime odd
if (i % j == 0):
p = False
break
j=j+1
# add the number in the list only if p is true
if p:
Prime_list.append(i)
print(Prime_list)

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.")

#Call the function


simpleFunc()
Output:
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

#create two variables


x = 34
y = 45

# call a function and


# store it output in a variable
z = add(x,y)
print(z)

#call the function again


z = add(x, 5)
print(z)
Output:
79
39

1.8.2 Lambda function


Lambda functions are anonymous functions in Python. This function is defined without any name. Besides
this, the keyword lambda is used instead of the keyword def. Like a higher-order function, a lambda
function can take any number of arguments or parameters. On the contrary, it can have only one
statement. The syntax of lambda functions:
lambda parameters : a statement

The example of a lambda function is mentioned below.

49
#create a lambda function
cube = lambda x: x*x*x

print ("The cube of 9 is", cube(9))

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

#create variable for dimensions of a box


length = 5
breadth = 3
height = 4

#create lambda functions


#to calculate the area of different faces
lb = lambda l, b : l * b
bh = lambda b, h : b * h
lh = lambda l, h : l * h

#call the function


tsa = tsa_function(bh(breadth, height), lh(length, height),lb(length,
breadth))
print("Total Surface area of Box is", tsa)
Output:
Total Surface area of Box is 7200

1.8.3 Scope of Variable


Depending upon the location of the declaration of a variable in a program, the variable may or may not
be accessible at all locations. The scope means whether a variable’s value can be determined or changed
from any other portion of the program. Such accessibility of variables are categorised into two basic types:

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.

#create is a global variable.


average = 0; # This average is a global variable

#define a function with a local variable


def AvgFunc( para1, para2 ):
average = (para1 + para2)/2; # This average is a local variable.
print ("Inside function, local average =", average)
return average

# Now you can call AvgFunc function


AvgFunc( 10, 20 )
print ("Outside function, global average =", average)

Output:

Inside function, local average = 15.0


Outside function, global average = 0

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.

2.1.1 Creating Class


Python is also an object-oriented programming language. As a result, it supports the concept of classes
and objects. The syntax for the declaration of classes in Python is very simple and straightforward, as
stated below.

class class_name:
#class_variables

def method0(arg0, arg1, ..., argN):


#statements
def method2(arg0, arg1, ..., argN):
#statements
.
.
.
def methodN(arg0, arg1, ..., argN):
#statements

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')

#create an object of the class


Kabir = student()

# Call object's result() method


[Link]()
Output:
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.

2.1.2 Special function names


The names of functions in a class starting with double underscore __ are called special functions. Such
functions have special purposes. The naming format for such functions is __SpecialName__. It is done to
avoid name conflict in programs. Some such functions are __init__, __del__, __str__, __repr__, __cm__ and
__nonzero__.
This section describes only one special function of all listed above, i.e. __init__() function. It is known as a
constructor. Constructor is called automatically whenever a new object is instantiated. Commonly, it is
used to initialise all the variables. The following examples show its usage.
#create a class
class student:
#create a variable
roll_no = 0
#create a variable
records = {}

#Special function constructor to initialise all the variables


def __init__(self, name, age):
[Link] = name
[Link] = age
student.roll_no += 1
[Link][student.roll_no] = [name, age]
def displayCount(self):
print ("Total student:", student.roll_no)

53
def displaystudent(self):
print ("Name:", [Link], ", Age:", [Link])

#create first object of student class


pupil_1 = student("Adam", 14)

#create second object of student class


pupil_2 = student("David", 15)

#create Third object of student class


pupil_3 = student("Simran", 13)

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

#call the function from the module


result = [Link](3,4)
print("The sum of two numbers:", result)
Output:
The sum of two numbers: 7
Note: To ensure that this code will work, keep both files in the same folder or directory. The Python folder
is highly recommended.

2.2.2 Renaming a Module


In some cases, module names are inconveniently long or non-intuitive to a programmer. In such a case,
a module name can be renamed using the keyword as. The general syntax structure of it is mentioned
below.
import Module_Name as New_Name

As mentioned above, the module rename is implemented in the below given example.
#Import the module and rename it
import ExampleModule as ExModule

#call the function from the module


result = [Link](3,4)
print("The sum of two numbers:", result)
Output:
The sum of two numbers: 7

2.2.3 From ... Import Statement


Sometimes, a part or parts of a module are needed in a program instead of the whole module. This can
be accomplished with the help of the keyword from along with import statements. The general syntax of
this is given below.
from moduleName import name1, name2, …, NameN

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)"]

def speed(d, t):


result = d/t
return result

def acceleration(s, t):


result = s/t
return result

def momentum(s, m):


result = s*m
return result

def force(acc, m):


result = acc * m
return result

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

#To know the argument of momentum function


print(function_detail)

#create variables
speed = 72
mass = 1500

#Use momentum function to calculate


result = momentum(speed, mass)
print("The momentum is", result)
Output:
['speed(distance, time)', 'acceleration(speed, time), momentum(speed,
mass)', 'force(acceleration, mass)']
The momentum is 108000

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 *

#To know the argument of momentum function


print(function_detail)

#create variables
time = 12
distance = 360
mass = 1200

#call the function from the module


V = speed(distance, time)
print("speed =", V)

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

2.2.5 dir( ) Function


Modules also enable a programmer to use already existing Python codes developed by another
programmer or community of programmers. Codes can be imported from multiple modules to a program
without any difficulty. It increases productivity and helps programmers avoid wasting time-solving
problems, which have already been solved. Working on a project requires multiple libraries/modules that
have been developed by someone else. In such a case, knowing each name that is defined in a
module/library is vital for the effective utilisation of the module. A built-in function called dir() is used to
get this information. It takes the name of a module as an argument and returns a sorted list of names
defined in the module.

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']

2.3 File Handling


Like many other programming languages, Python also supports file handling. Unlike them, the procedure
for this in Python is a lot more manageable and intuitive. It means using Python, files on a computer can
be created, read, written and edited. Commonly, it is used to store data on the computer permanently. As
it is already understood, the data stored in the variables get destroyed once the program execution has
been completed or interrupted for any reason. File handling is used to retrieve or store data whenever a
program is executed. To do that, file handling has a collection of functions for creating, reading, updating
and deleting files.
The below-given order of operations is required to be followed to perform any file handling task.
1. File open
2. Read/write/append/create
3. File close

2.3.1 Files Opening and Closing


Before reading and writing a file, the file needs to be opened. A built-in function open() is required to be
used to do this. This function takes two arguments: filename and mode. The general syntax for it is
mentioned below.

File_object = open(filename, mode)

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()

2.3.2 File Read


This section describes the procedure by which a file on the computer can be read. For that, first, the file
is required to be opened in reading mode using the open() function by passing two arguments: the file
name and the reading mode, i.e. “r”. Afterwards, another built-in function is used to read the file, and it is
read(). Once the reading operation is over, the close() function is used to close the file. The following
examples demonstrate this.

59
#first, make sure that "[Link]" must be
#available in the folder

#create file object to read the file


txt_file = open("[Link]", "r") #return error
#if "[Link]" does not exist

#read the file using the read() function


print(txt_file.read())

#close the file


txt_file.close()

Output:
Hello world!

The complete path is required when the file is located somewhere else on the computer, as shown below.

#first, make sure that "Roll_23.txt" must be


#available in the specified folder

#create file object to read the file


txt_file = open("D:\students\Roll_23.txt", "r") #return error
#if "Roll_23.txt" does not exist

#read the file using the read() function


print(txt_file.read())

#close the file


txt_file.close()

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

#create file object to read the file


txt_file = open("D:\students\Roll_23.txt", "r") #return error if "Roll
_23.txt" does not exist

#read the file using the read() function


print(txt_file.read(12)) # it will read first 12 characters only

#close the file


txt_file.close()

Output:
Name: Kabir

2.3.3 File Write/Create


Apart from open() and close() functions, the built-in write() function is also required to write or create a
specified file. For example,
#create file object to write the file
txt_file = open("D:\students\[Link]", "w") #a new file is creat
ed
#if "[Link]" does not exist

#write the file using the write() function


txt_file.write("salutation!")

#close the file


txt_file.close()

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

#write the file using the write() function


txt_file.write("how-do-you-do!")

#close the file


txt_file.close()

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.

The below-given program appends the mentioned file above.


#create file object to append the file
txt_file = open("[Link]", "a")
#a new file is created if "[Link]" does not exist

#append the file txt_file.write("One very famous saying is associated


with the apple, an apple a day keeps the doctor away.")

#close the file object


txt_file.close()

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

#call the remove() function to delete a file


[Link]("[Link]")

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

#first verify the existence of the file


if [Link]("[Link]"):
#call the remove() function to delete a file
[Link]("[Link]")
else:
print("Please check. The file does not exist!")

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

#call the rmdir() function to delete a folder


[Link]("D:\Folder_docs")
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

63

You might also like