I 1 Python SLM PU Edited
I 1 Python SLM PU Edited
NAAC 'A++' Grade - State University - NIRF Rank 56 – State Public University Rank 25
SALEM - 636 011, Tamil Nadu, India.
PERIYAR UNIVERSITY
CORE – I
Python Programming
Prepared by:
Centre for Distance and Online Education (CDOE)
Periyar University, Salem – 11.
CDOE –ODL B.Sc CS – SEMESTER I PYTHON PROGRAMMING
SYLLABUS
PYTHON PROGRAMMING
Unit I : Basics of Python Programming: History of Python-Features of Python-Literal
-Constants-Variables - Identifiers–Keywords-Built-in Data Types-Output Statements
– Input Statements-Comments – Indentation- Operators-Expressions -Type
conversions. Python Arrays: Defining and Processing Arrays – Array methods.
Unit III: Functions: Function Definition – Function Call – Variable Scope and its
Lifetime-Return Statement. Function Arguments: Required Arguments, Keyword
Arguments, Default Arguments and Variable Length Arguments- Recursion. Python
Strings: String operations- Immutable Strings - Built-in String Methods and Functions
- String Comparison. Modules: import statement- The Python module – dir() function
– Modules and Namespace – Defining our own modules
Unit V : Python File Handling: Types of files in Python - Opening and Closing files-
Reading and Writing files: write() and writelines() methods- append() method –
read() and readlines() methods – with keyword – Splitting words – File methods - File
Positions- Renaming and deleting files
CDOE –ODL B.Sc CS – SEMESTER I PYTHON PROGRAMMING
TABLE OF CONTENTS
UNIT TOPICS PAGE
1 Basics of Python Programming and Python Arrays 1
2 Control Statements and Jump Statements 47
3 Functions, Strings and Modules 66
4 Lists, Tuples and Dictionaries 94
5 Python File Handling 122
CDOE - ODL B.Sc Computer Science – SEMESTER I UNIT - 1
PYTHON PROGRAMMING
UNIT 1 – PYTHON PROGRAMMING
Basics of Python Programming: History of Python-Features of Python-
Literal -Constants-Variables - Identifiers–Keywords-Built-in Data Types-
Output Statements – Input Statements-Comments – Indentation-
Operators-Expressions -Type conversions. Python Arrays: Defining and
Processing Arrays – Array methods.
Unit Objectives
In this unit, leaners will have a brief understanding of the history and features of
python programming. The basic concepts that are need for any programming languages
like constants, literals, keywords and how to declare a variable in python will be
discussed. Along with the basic data types that are supported in python programming.
The way how to use the input, output statement and how data type conversion of
variables in done in python. Finally the unit ends with how to create and process Arrays
and the methods used for array in python.
Python was first developed by Guido van Rossum in the late 80‟s and early 90‟s
at the National Research Institute for Mathematics and Computer Science in the
Netherlands. It has been derived from many languages such as ABC, Modula-3, C,
C++, Algol68, SmallTalk, UNIX shell and other scripting languages.Since early 90‟s
Python has been improved tremendously. Its version 1.0 was released in 1991, which
introduced several new functional programming tools. While version 2.0included list
comprehension was released in 2000 by the Be Open Python Labs team.
Python 2.7 which is still used today will be supported till 2020. Currently Python
3.6.4 is already available. The newer versions have better features like flexible string
representation etc., Although Python is copyrighted, its source code is available under
GNU General Public License (GPL) like that Perl. Python is currently maintained by a
core development team at the institute which is directed by Guido Van Rossum. These
days, from data to web development, Python has emerged as very powerful and
popular language. It would be surprising to know that python is actually older than Java,
R and JavaScript.
Simple: Reading a program written in Python feels almost like reading english.
The main strength of Python which allows programmer to concentrate on the
solution to the problem rather than language itself.
Easy to Learn: Python program is clearly defined and easily readable. The
structure of the program is simple. It uses few keywords and clearly defined
syntax.
Versatile: Python supports development of wide range of applications such as
simple text processing, WWW browsers and games etc..
Free and Open Source: It is a Open Source Software. So, anyone can freely
distribute it, read the source code, edit it, and even use the code to write new
(free) programs.
High-level Language: While writing programs in Python we do not worry about
the low-level details like managing memory used by the program.
Interactive: Programs in Python work in interactive mode which allows
interactive testing and debugging of pieces of code. Programmer can easily
interact with the interpreter directly at the python prompt to write their programs.
Portable: It is a portable language and hence the programs behave the same on
wide variety of hardware platforms with different operating systems.
Python literals or constants are the notation for representing a fixed value in
source code. In contrast to variables, literals (123, 4.3, "Hello") are static values or you
can say constants which do not change throughout the operation of the program or
application.
Example
x=10
Here 10 is a literal as numeric value representing 10, which is directly stored in
memory. However,
y=x*2
Here, even if the expression evaluates to 20, it is not literally included in source
code. You can also declare an int object with built-in int() function. However, this is also
an indirect way of instantiation and not with literal.
x=(int)10
Number
The value of a literal constant can be used directly in programs. For example, 7,
3.9, 'A', and "Hello" are literal constants. Numbers refers to a numeric value. You can
use four types of numbers in Python program- integers, long integers, floating point and
complex numbers. Numbers like 5 or other whole numbers are referred to as integers.
Bigger whole numbers are called long integers.
For example, 535633629843L is a long integer. Numbers like are 3.23 and
91.5E-2 are termed as floating point numbers. Numbers of a + bj form (like -3 + 7j)
are complex numbers.
A Literals Boolean type can have one of the two values- True or False.
String
A string is a group of characters. Using Single Quotes ('): For example, a string
can be written as 'HELLO'. Using Double Quotes ("): Strings in double quotes are
exactly same as those in single quotes. Therefore, 'HELLO' is same as "HELLO". Using
Triple Quotes (''' '''): You can specify multi-line strings using triple quotes. You can use
as many single quotes and double quotes as you want in a string within triple quotes.
Unicode Strings
Unicode is a standard way of writing international text. That is,if you want to write
some text in your native language like hindi,then you need to have a Unicode-enable
text editor. Python allows you to specify Unicode text by prefixing the string with a u or
U. For Example: u”Sample Unicode string” Note :The „U‟ prefix specifies that the file
contains text written in language other than English
Escape Sequences
Some characters (like ", \) cannot be directly included in a string. Such characters
must be escaped by placing a backslash before them.
Raw Strings
If you want to specify a string that should not handle any escape sequences and
want to display exactly as specified then you need to specify that string as a raw string.
A raw string is specified by prefixing r or R to the string.
Example
>>>print(R ”What\’s is your name?”)
1.1.4 – Variables
Every one of the characters with the exception of the main person might be a
letter set of lower-case(a-z), capitalized (A-Z), highlight, or digit (0-9).
White space and special characters (!, @, #, %, etc.) are not allowed in the
identifier name. ^, &, *).
Identifier name should not be like any watchword characterized in the language.
Example
number = 10
site_name = 'programiz.pro'
print(site_name)
Output
'programiz.pro'
x=y=z=50
Local Variable
The variables that are declared within the function and have scope within the
function are known as local variables. Let's examine the following illustration.
Example -
def add(): # Defining local variables. They has scope only within a function
a = 20
b = 30
c=a+b
Output:
The sum is: 50
Global Variables
Global variables can be utilized all through the program, and its extension is in
the whole program. Global variables can be used inside or outside the function. By
default, a variable declared outside of the function serves as the global variable. Python
gives the worldwide catchphrase to utilize worldwide variable inside the capability. The
function treats it as a local variable if we don't use the global keyword.
Example -
x = 101 # Declare a variable and initialize it
def mainFunction(): # Global variable in function
# printing a global variable
global x
print(x)
# modifying a global variable
x = 'Welcome To Python’
print(x)
mainFunction()
print(x)
Output:
101
Welcome To Python
Welcome To Python
1.1.5 – Identifiers
1.1.6 – Keywords
Python has a list of reserved words known as keywords. Every keyword has a
specific purpose and use. In the upcoming chapters, we will look into the use of these
keywords in programming. A list of reserved keywords in Python are
The data stored in the memory can be of many types. For example, a person’s
name is stored as an alphabetic value and its address is stored as an alphanumeric
value. Sometimes, we also need to store answer in terms of only ‘yes’ or ‘no’, i.e., true
or false. This type of data is known as Boolean data.
Python has six basic data types which are as follows:
1. Numeric
2. String
3. List
4. Tuple
5. Dictionary
6. Boolean
Numeric
Numeric data can be broadly divided into integers and real numbers (i.e., fractional
numbers). Integers can themselves be positive or negative. Unlike many other
programming languages, Python does not have any upper bound on the size of
integers. The real numbers or fractional numbers are called floating point numbers in
programming languages. Such floating point numbers contain a decimal and a fractional
part.
Example
>>> num1=2
>>>num2=2.5
>>>num1
2 # Output
>>>num2
2.5 # Output
Note : In all the earlier versions of Python 3, slash (/) operator worked differently. When
both numerator and denominator are integers, then the result will be an integer. The
slash operator removes the fraction part.
The result becomes a floating number when either the numerator or the denominator is
a floating number. When both the numerator and the denominator are floating numbers,
the result is again a floating number. The division operator provides accurate results
even when both the numerator and the denominator are integers.
Example
>>> 5/2
1.5 # Output
String
Besides numbers, strings are another important data type. Single quotes or
double quotes are used to represent strings. A string in Python can be a series or a
sequence of alphabets, numerals and special characters. Similar to C, the first
character of a string has an index 0.
There are many operations that can be performed on a string. There are several
operators such as slice operator ([]) and [:]), concatenation operator (+), repetition
operator (*), etc. Slicing is used to take out a subset of the string, concatenation is used
to combine two or more than two strings and repetition is used to repeat the same string
several times.
Example
>>>sample_string =”Hello” # store string value
>>>sample_string # display string value
‘Hello’ # Output
>>>sample_string + “World” # use of + operator
‘HelloWorld’ # Output
>>>sample_string * 3 # use of * operator
‘HelloHelloHello’ # Output
Python also provides slice operators ([] and [:]) to extract substring from the
string. In Python, the indexing of the characters starts from 0; therefore, the index value
of the first character is 0.
Syntax
sample_string[start : end <:step>] #step is optional
Example
>>>sample_string=”Hello”
>>>sample_string[1] # display 1st index element.
‘e’ # Output
>>>sample_string[0:2] # display 0 to 1st index elements
‘He’ # Output
>>>sample_string = "HelloWorld"
>>>sample_string[1:8:2] # display all the alternate characters between index 1
to 8. ie, 1,3,5,7
'elWr' # Output
List
List is the most used data type in Python. A list can contain the same type of
items. Alternatively, a listcan also contain different types of items. A list is an ordered
and indexable sequence. To declare a list in Python, we need to separate the items
using commas and enclose them within square brackets([]). The list is somewhat similar
to the array in C language. However, an array can contain only the same type of items
while a list can contain different types of items.
Similar to the string data type, the list also has plus (+), asterisk (*) and slicing [:]
operators for concatenation, repetition and sub-list, respectively.
Example
>>>first=[1,”two”,3.0,”four”] # 1 list
>>>second=[“five”, 6] # 2 stnd list
>>>first # display 1
[1, ‘two’, 3.0, ‘four’] # Output
>>>first+secondst list # concatenate 1and 2 list
[1, ‘two’, 3.0, ‘four’, ‘five’, 6] # Output
>>>second * 3 # repeat 2nd list
Tuple
Similar to a list, a tuple is also used to store sequence of items. Like a list, a tuple
consists of items separated by commas. However, tuples are enclosed within
parentheses rather than within square brackets.
Example
>>>third=(7, “eight”,9, 10.0)
>>>third
(7, ‘eight’, 9, 10.0) # Output
Lists and tuples have the following differences:
In lists, items are enclosed within square brackets [], whereas in tuples, items are
enclosed within parentheses ().
Lists are mutable whereas Tuples are immutable. Tuples are read only lists. Once the
items are stored, the tuple cannot be modified.
Dictionary
It is the same as the hash table type. The order of elements in a dictionary is
undefined. But, we can iterate over the following:
1. The keys
2. The values
3. The items (key-value pairs) in a dictionary
Example
>>> dict1 = {1:"first line", "second":2} # declare dictionary
>>>dict1[3] = "third line" # add new item
Boolean
In a programming language, mostly data is stored in the form of alphanumeric
but sometimes we need to store the data in the form of ‘Yes’ or ‘No’. In terms of
programming language, Yes is similar to True and No is similar to False. This True and
False data is known as Boolean Data and the data types which stores this Boolean data
are known as Boolean Data Types.
Example
>>> a = True
>>>type(a)
<type ‘bool’>
>>> x = False
>>>type(x)
<type ‘bool’>
Python print() function prints the message to the screen or any other standard
output device. In this article, we will cover about print() function in Python as well as it’s
various operations.
Syntax
print(value(s), sep= ‘ ‘, end = ‘\n’, file=file, flush=flush)
Parameters:
value(s): Any value, and as many as you like. Will be converted to a string
before printed
Example
name = "John"
age = 30
print("Name:", name)
print("Age:", age)
Output:
Name: John
Age: 30
You can pass variables, strings, numbers, or other data types as one or more
parameters when using the print() function. Then, these parameters are represented as
strings by their respective str() functions. To create a single output string, the
transformed strings are concatenated with spaces between them. In this code, we are
passing two parameters name and age to the print function
Example
name = "Alice"
age = 25
print("Hello, my name is", name, "and I am", age, "years old.")
Output
Hello, my name is Alice and I am 25 years old.
String literals in Python’s print statement are primarily used to format or design
how a specific string appears when printed using the print() function.
\n: This string literal is used to add a new blank line while printing a statement.
“”: An empty quote (“”) is used to print an empty line.
The end keyword is used to specify the content that is to be printed at the end of
the execution of the print() function. By default, it is set to “\n”, which leads to the
change of line after the execution of print() statement.
Example
#using print() with end and without end parameters.
# This line will automatically add a new line before the next print statement
print ("Python Programming is OOP ")
# This print() function ends with "**" as set in the end argument.
print ("Python Programming is OOP ", end= "&&")
print("Welcome to Python World")
Output:
Python Programming is OOP
Python Programming is OOP&&Welcome to Python World
Print concatenation
>>>a,b,=10,1000
print('The value of a is {} and b is {}'.format(a,b))
The value of a is 10 and b is 1000
The print() function can accept any number of positional arguments. To separate
these positional arguments, the keyword argument “sep” is used.
Example
a=12
b=12
c=2024
print(a,b,c,sep="-")
Output:
12-12-2024
In a programming language, the input from keyboard by user plays the most
important role in executing a program. There is hardly any program which executes
without some input. The input in many programs is prompted by the user and the user
uses the keyboard in order to provide input for the program to execute. Python
programming language also provides the facility to user to provide input from keyboard.
Prompting the input from user in Python is through function has an optional
parameter, which is the prompt string. When the input() input() function. input() function
is called, in order to take input from the user then the execution of program halts and
waits for the user to provide an input. The input is given by the user through keyboard
and it is ended by the return key. input() function interprets the input provided by the
user, i.e. if user provides an integer value as input then the input function will return this
integer value. On the other hand, if the user has input a String, then the function will
return a string.
Example
>>>name = input(“What is your Name?”)
Hello John!
32 #Output
>>>print hobby
[‘playing’, ‘travelling’]
>>>type(name)
1.1.10 – Comments
Just like other programming languages, Python allows you to add comments in
the code. Comments are used by the programmer to explain the piece of code to others
as well as to himself in a simple language. Every programming language makes use of
some special character for commenting, so does Python.
Python uses the hash character (#) for comments. Putting # before a text
ensures that the text will not be parsed by the interpreter. Comments do not affect the
programming part and the Python interpreter does not display any error message for
comments. Comments show up as it is in the programming. It is a good practice to use
comments for program documentation in your program so that it becomes easier for
other programmers to maintain or enhance the program when required.
In the above example, ‘addition’ is written without the Hash mark. As a result, the
interpreter accepts the word ‘addition’ as part of programming. Since ‘addition’ is not a
command in Python, an error message is displayed.
17 # Output
Now, in this example, ‘addition’ is written with a Hash mark. Hence, the
interpreter understands it as a comment and does not display any error message.
1.1.11 – Indentation
In Python, indentation refers to the spacing at the beginning of a line of code that
determines its grouping and hierarchy within the program’s structure. Unlike many
programming languages that use braces ({}) or other explicit symbols to denote code
blocks, Python uses indentation to signify the beginning and end of blocks of code.
Python’s default indentation spaces are four spaces. The number of spaces,
however, is entirely up to the user. However, a minimum of one space is required
to indent a statement.
Indentation is not permitted on the first line of Python code.
Python requires indentation to define statement blocks.
A block of code must have a consistent number of spaces.
To indent in Python, whitespaces are preferred over tabs. Also, use either
whitespace or tabs to indent; mixing tabs and whitespaces in indentation can
result in incorrect indentation errors.
Example
site = 'prepbytes'
if site == 'prepbytes':
print('Logging on to prepbytes...')
else:
Output
Logging on to prepbytes...
All set !
Example 2
j=1
while(j<= 5):
print(j)
j=j+1
Output
1.1.12 – Operators
Operators are used to perform operations on variables and values. Python supports
following operators -
o Arithmetic operators
o Comparison operators
o Assignment Operators
o Logical Operators
o Bitwise Operators
o Membership Operators
o Identity Operators
Arithmetic Opertors
Operator Description
- (Subtraction) It is used to subtract the second operand from the first operand. If the
first operand is less than the second operand, the value results
negative. For example, if a = 20, b = 5 => a - b = 15
/ (divide) It returns the quotient after dividing the first operand by the second
operand. For example, if a = 20, b = 10 => a/b = 2.0
% (reminder) It returns the reminder after dividing the first operand by the second
operand. For example, if a = 20, b = 10 =>a%b = 0
// (Floor It provides the quotient's floor value, which is obtained by dividing the
division) two operands.
Example
Output:
Comparison Operators
Operator Description
== If the value of two operands is equal, then the condition becomes true.
!= If the value of two operands is not equal, then the condition becomes
true.
<= The condition is met if the first operand is smaller than or equal to the
second operand.
>= The condition is met if the first operand is greater than or equal to the
second operand.
> If the first operand is greater than the second operand, then the
condition becomes true.
< If the first operand is less than the second operand, then the condition
becomes true.
Example:
Output:
Assignment Operators
Using the assignment operators, the right expression's value is assigned to the
left operand. There are some examples of assignment operators like =, +=, -=, *=, %=,
**=, //=. In the below table, we explain the works of the operators.
Operator Description
+= By multiplying the value of the right operand by the value of the left
operand, the left operand receives a changed value. For example, if a = 10,
b = 20 => a+ = b will be equal to a = a+ b and therefore, a = 30.
-= It decreases the value of the left operand by the value of the right operand
and assigns the modified value back to left operand. For example, if a = 20,
b = 10 => a- = b will be equal to a = a- b and therefore, a = 10.
*= It multiplies the value of the left operand by the value of the right operand
and assigns the modified value back to then the left operand. For example,
if a = 10, b = 20 => a* = b will be equal to a = a* b and therefore, a = 200.
%= It divides the value of the left operand by the value of the right operand and
assigns the reminder back to the left operand. For example, if a = 20, b =
10 => a % = b will be equal to a = a % b and therefore, a = 0.
**= a**=b will be equal to a=a**b, for example, if a = 4, b =2, a**=b will assign
4**2 = 16 to a.
//= A//=b will be equal to a = a// b, for example, if a = 4, b = 3, a//=b will assign
4//3 = 1 to a.
Example:
print('a=b:', a==b)
print('a+=b:', a+b)
print('a-=b:', a-b)
print('a*=b:', a*b)
print('a%=b:', a%b)
print('a**=b:', a**b)
print('a//=b:', a//b)
Output:
a=b: False
a+=b: 38
a-=b: 26
a*=b: 192
a%=b: 2
a**=b: 1073741824
a//=b: 5
Logical Operators
Operator Description
and The condition will also be true if the expression is true. If the two
expressions a and b are the same, then a and b must both be true.
or The condition will be true if one of the phrases is true. If a and b are the two
expressions, then an or b must be true if and is true and b is false.
not If an expression a is true, then not (a) will be false and vice versa.
Example:
Bitwise Operators
The two operands' values are processed bit by bit by the bitwise operators. The
examples of Bitwise operators are bitwise OR (|), bitwise AND (&), bitwise XOR (^),
negation (~), Left shift (<<), and Right shift (>>).
Example
if a = 7
b=6
then, binary (a) = 0111
binary (b) = 0110
~ a = 1000
Let, Binary of x = 0101
Binary of y = 1000
Bitwise OR = 1101
8421
1 1 0 1 = 8 + 4 + 1 = 13
& (binary A 1 is copied to the result if both bits in two operands at the same
and) location are 1. If not, 0 is copied.
| (binary or) The resulting bit will be 0 if both the bits are zero; otherwise, the
resulting bit will be 1.
^ (binary If the two bits are different, the outcome bit will be 1, else it will be 0.
xor)
~ (negation) The operand's bits are calculated as their negations, so if one bit is 0,
the next bit will be 1, and vice versa.
<< (left shift) The number of bits in the right operand is multiplied by the leftward shift
of the value of the left operand.
>> (right The left operand is moved right by the number of bits present in the right
shift) operand.
Example:
Output:
a&b: 4
a|b: 7
a^b: 3
~a: -6
a<>b: 0
Membership Operators
The membership of a value inside a Python data structure can be verified using
Python membership operators. The result is true if the value is in the data structure;
otherwise, it returns false.
Operator Description
not in If the first operand is not present in the second operand, the evaluation is true
(list, tuple, or dictionary).
Example
x = ["Rose", "Lotus"]
Output:
Identity Operators
These operators are used to check whether both operands are same or not.
Suppose, x stores a value 20 and y stores a value 40. Then x is y return false and x not
is y returns true.
Operator Description
is not If the references on both sides do not point at the same object, it is
determined to be true.
Example
a = ["Rose", "Lotus"]
b = ["Rose", "Lotus"]
c=a
print(a is c)
print(a is not c)
print(a is b)
print(a is not b)
print(a == b)
print(a != b)
Output:
True
False
False
True
True
False
Operator Precedence
The order in which the operators are examined is crucial to understand since it
tells us which operator needs to be considered first. Below is a list of the Python
operators' precedence tables.
Operator Description
* / % // the division of the floor, the modules, the division, and the
multiplication.
<= <>>= Comparison operators (less than, less than equal to, greater than,
greater then equal to).
1.1.13 – Expressions
Example: 8 + 9 – 2
2. Integral Expressions: One that produces an integer result after evaluating the
expression.
Example: a = 10
Example: a * b / 2.0
Example: c = a>b
5. Logical Expressions: One that combines two or more relational expressions and
returns a value as True or False.
Example: x = y&z
Example: c = a + b or c = 10
Example
a = 20
b = 10
c = 15
d=5
e = (a + b) * c / d
e = ((a + b) * c) / d
e = (a + b) * (c / d)
e = a + (b * c) / d
Output:
Value of (a + b) * c / d is 90.0
Value of (a + b) * (c / d) is 90.0
Value of a + (b * c) / d is 50.0
There may be times when you want to specify a type on to a variable. This can
be done with casting. Python is an object-orientated language, and as such it uses
classes to define data types, including its primitive types.
int() - constructs an integer number from an integer literal, a float literal (by
removing all decimals), or a string literal (providing the string represents a whole
number)
float() - constructs a float number from an integer literal, a float literal or a string
literal (providing the string represents a float or an integer)
str() - constructs a string from a wide variety of data types, including strings,
integer literals and float literals
Example - Integers:
x = int(1) # x will be 1
y = int(2.8) # y will be 2
z = int("3") # z will be 3
Example - Floats:
Example - Strings:
Let’s Sum Up
In this section we have studied history of Python Programming Language along
with its features. Python is a general purpose high level programming language. Python
was developed by Guido Van Rossam in 1989, while working at National Research
Institute at Netherlands. The official Date of Birth for Python is Feb 20th 1991. In
Python, an identifier (name) must begin with a letter or underscore and can include any
number of letters, digits, or underscore. Writing the name of a variable is called
declaring a variable whereas assigning a value to a variable is called initialising a
variable. In python you can reassign variables as many times as you want to change the
value stored in them. The level of indentation groups statements to form a block of
statements. A variable of Boolean type can have only one of the two values – True or
False.
The input function prompts the user to provide some information on which the
program can work and give the result. The print statement is used to display the output
screen. Comments are non-executable statements in a program. They are just added to
describe the statements in the program code.
a. # b. ! c. @ d. *
3. Which is not a reserved keyword in Python?
a. Insert b. Pass c. Class d. Lambda
4. What is the output of >>> 4+?
a. 4+ b. 4 c. 5 d. Invalid syntax
5. Which of the following is the floor division operator?
a. / b. % c. // d. \\
6. What will be the output of str[0:4] if str=”Hello”?
a. ‘Hello’ b. ‘H’ c. ‘Hel’ d. ‘Hell’
7. Which of the following is used to find the first index of search string?
a. .find(“string”) b. .search(“string”) c. (“string”).find d. (“string”).search
8. Which of the following is used to access single character of string?
a. [:] b. () c. [.] d. []
9. Which of the following will be printed? x =4.5 y =2 print x//y
a. 2.0 b. 2.25 c. .25 d. 0.5
10. ________ an integer value that represents an element in a sequence
a. index b.item c.list d.id
Array is a container which can hold a fix number of items and these items should be
of the same type. Most of the data structures make use of arrays to implement their
algorithms. Following are the important terms to understand the concept of Array.
Python's standard library has array module. The array class in it allows you to
construct an array of three basic types, integer, float and Unicode characters.
Syntax
import array
initializer − array initialized from the optional value, which must be a list, a bytes-
like object, or iterable over elements of the appropriate type.
Return type
Example
from array import *
for x in array1:
print(x)
OUTPUT:
10
20
30
40
50
print (array1[0])
print (array1[2])
Output
10
30
Insertion Operation
Insert operation is to insert one or more data elements into an array. Based on
the requirement, a new element can be added at the beginning, end, or any given index
of array. Here, we add a data element at the middle of the array using the python in-built
insert() method.
Example
array1.insert(1,60)
for x in array1:
print(x)
Output
10
60
20
30
40
50
Deletion Operation
Deletion refers to removing an existing element from the array and re-organizing
all elements of an array. Here, we remove a data element at the middle of the array
using the python in-built remove() method.
Example
array1.remove(40)
for x in array1:
print(x)
Output
10
20
30
50
Search Operation
You can perform a search for an array element based on its value or its index.
Here, we search a data element using the python in-built index() method. When we
compile and execute the below program, it produces the following result which shows
the index of the element. If the value is not present in the array then the program returns
an error.
Example
array1 =array('i',[10,20,30,40,50])
print(array1.index(40))
Output
3
Update Operation
Update operation refers to updating an existing element from the array at a given
index. Here, we simply reassign a new value to the desired index we want to update.
Example
array1[2] =80
for x in array1:
print(x)
Output
10
20
80
40
50
Let Us Sum Up
In this section, the learners had the introduction to array concepts, how to create
an array and the different types of array because an array is a collection of elements of
same type. The way to insert an element into array and how to access the elements in
the array were discussed. The various methods that are available for array processing
were also mentioned like how to pop an array element.
12. The type code used to create floating point number in a array is ____
UNIT SUMMARY
In this unit we have studied the history and various features of Python
Programming Language which made so popular to be used in current upcoming
applications by the developer. Python is recommended as first programming language
for beginners. Python is an example of Dynamically typed programming language. The
literal constants that we can be used directly in Programming Language which made so
popular to be used in current upcoming applications by the developer. In Python, the
Hash character (#) is used for commenting. Codes or texts that come after the hash
character are not considered as a part of the program. We briefly discuss how
Operators work using the program code for each operator in Python.
GLOSSARY
COMMENT: The part of the program not executed by the interpreter. It is used by
other persons to understand the program thoroughly.
DICTIONARY: A mapping of keys to their corresponding values.
FLOATING POINT: A type of numeral that has a fractional part.
INDEX: An integer value that represents an element in a sequence.
INTEGER: A type of numeral that represents whole numbers including negative
numbers.
ITEM: An element or a value in a series.
ITERATION: The repetition of a set of statements or a piece of code.
KEYWORD: A word that is reserved in a programming language for a specific
purpose. We cannot use keywords such as if and else as variable names.
OPERAND: The value on which an operator operates
EXERCISES
1. What is the output of print list[2] when list = [‘abcd’, 2.23, ‘john’]?
2. How will you convert a string to an integer in Python?
3. What are the uses of //, **, *= operators in Python?
4. Identify the datatype is best suitable to represent the following data values
a)Number of days in the year
b)The circumference of a rectangle
c)Yours father salary
d)Distance between moon and earth
e)Name of your best friend
QUIZ - ANSWERS
1. c.array
2. a. #
3. a.insert
4. d.invalid syntax
5. c.//
6. a.’Hello’
7. a.find(“string”)
8. d.[]
9. a.2.0
10. a.index
11. array
12. f
13. 0
14. index()
15. remove()
SUGGESTED READINGS
REFERENCES
1. Reema Thareja,””Python Pogramming using Problem Solving approach”, Oxford
Higher Education,
PYTHON PROGRAMMING
UNIT 2- PYTHON PROGRAMMING
Control Statements: Selection/Conditional Branching statements: if,
if-else, nested if and if-elif-else statements. Iterative Statements:
while loop, for loop, else suite in loop and nested loops. Jump
Statements: break, continue and pass statements.
Page
Section Topic
No.
UNIT - II
Unit Objectives
Section 2.1 Control Statements 48
2.1.1 Selection/Conditional Branching statements 49
2.1.1.1 If-statements 49
2.1.1.2 If-else statements 50
2.1.1.3 Nested if 51
2.1.1.4 if-elif-else statements 53
2.1.2 Iterative Statements 54
2.1.2.1 while loop 54
2.1.2.2 for loop 56
2.1.2.3 else suite in loop and nested loops 58
Let Us Sum Up
Check Your Progress
Section 2.2 Jump Statements 60
2.2.1 Break statement 60
2.2.2 Continue statement 60
2.2.3 Pass statement 61
Let Us Sum Up
Check Your Progress
2.3 Unit- Summary 63
2.4 Glossary 63
UNIT OBJECTIVES
In this unit, the learners will have elaborative idea about the declaration of
Control Statements, Loop statements and Jump statements. The different types of
selection or conditional branching statements like if, if-else, nested if, if-elif-else will
be discussed with simple example. The two types of iterative statements like for and
while will be discussed with else suite in loop / nested loop which is a new concept in
python language. The unit ends its discussion with the use and scope of jump
statements like break, continue and pass.
The decision control statements usualy jumps, from one part of the code to
another depending on whether a particular condition is satisfied or not. That is, they
allow you to execute statements selectively based on certain decisions. Such type of
decision control statements are known as selection control statements or conditional
branching statements. Python language supports different types of conditional
branching statements which are as follows:
1. If statement
2. If-else statement
3. Nested if statement
4. If-elif-else statement
2.1.1.1 – if statements
Example
num = int(input("enter the number:"))
if num%2 == 0:
print("The Given number is an even number")
Output:
Enter a: 100
Enter b: 120
Enter c: 130
From the above three numbers given c is largest
The if-else statement provides an else block combined with the if statement
which is executed in the false case of the condition.
situation when you want to check for another condition after a condition resolves to
true. In such a situation, you can use the nested if construct. In a nested if construct,
you can have an if...elif...else construct inside another if...elif...else construct.
if expression1:
statement(s)
if expression2:
statement(s)
else:
if expression3:
statement(s)3
else
statement(s)
Example
num=8
print ("num = ",num)
if num%2==0:
if num%3==0:
print ("Divisible by 3 and 2")
else:
print ("divisible by 2 not divisible by 3")
else:
if num%3==0:
print ("divisible by 3 not divisible by 2")
else:
print ("not Divisible by 2 not divisible by 3")
Output
num = 8
divisible by 2 not divisible by 3
num = 15
The elif statement enables us to check multiple conditions and execute the
specific block of statements depending upon the true condition among them. We can
have any number of elif statements in our program depending upon our need.
However, using elif is optional.
elif number==100:
print("The given number is equal to 100");
else:
print("The given number is not equal to 10, 50 or 100");
Output:
Syntax
while expression:
statement(s)
As soon as the expression becomes false, the program control passes to the line
immediately following the loop. The following flow diagram illustrates the while loop
Example
In Python, the for Statement runs the code block each time it traverses a
series of elements. The loop_control_var is the parameter that determines the
element's value within the iterable sequence on each iteration. When a sequence
contains expression statements, they are processed first. The first element in the
sequence is then assigned to the iterating variable iterating_variable. From that point
onward, the planned block is run. Each element in the sequence is assigned to
iterating_variable during the statement block until the sequence as a whole is
completed. Using indentation, the contents of the Loop are distinguished from the
remainder of the program.
Example -find the sum of squares of each element of the list using for loop
# creating the list of numbers
numbers = [3, 5, 23, 6, 5, 1, 2, 9, 8]
# initializing a variable that will store the sum
sum = 0
# using for loop to iterate over the list
for num in numbers:
sum = sum + num ** 2
print("The sum of squares is: ", sum)
Output:
Example
languages = ['Swift', 'Python', 'Go']
# access elements of the list one by one
for i in languages:
print(i)
Output:
Swift
Python
Go
Example
language = 'Python'
for x in language: # iterate over each character in language
print(x)
Output
P
y
t
h
o
n
Example –
Let’s Sum Up
In this section, learners studied about the control statements in Python
Programming. The control statements include conditional and iterative statements.
There are four conditional statements like if, if-else, nested if and if-elif-else
statements. All the four statements are explained with simple example and their
expected output which helps the learner to understand the concept easily. Under
iterative statements while loop and for loop concepts are discussed.
4. _________ can be used when the number of times the statements in loop has
to be executed is not know in advance
5. for i in range(0,20):
print(____)
The break is a keyword in python which is used to bring the program control
out of the loop. The break statement breaks the loops one by one, i.e., in the case of
nested loops, it breaks the inner loop first and then proceeds to outer loops. In other
words, we can say that break is used to abort the current execution of the program
and the control goes to the next line after the loop. The break is commonly used in
the cases where we need to break the loop for a given condition.
Example
my_list = [1, 2, 3, 4]
count = 1
for item in my_list:
if item == 4:
print("Item matched")
count += 1
break
print("Found at location", count)
Output:
Item matched
Found at location 2
own in an efficient way. However, there might be occasions when we wish to leave
the current loop entirely, skip iteration, or dismiss the condition controlling the loop.
Example
for iterator in range(10, 21):
# If iterator is equals to 15, loop will continue to the next iteration
if iterator == 15:
continue
# otherwise printing the value of iterator
print( iterator )
Output:
10
11
12
13
14
16
17
18
19
20
2.2.3 – pass statement
The pass statement serves as a placeholder for future code, preventing errors
from empty code blocks.It's typically used where code is planned but has yet to be
written.
Example
def future_function():
pass
future_function()
Let’s Sum Up
In this section, learners studied about the control statements which includes
conditional and iterative statements. The conditional statements includes if, if-else,
nested if and if-elif-else statements. All the four statements are explained with simple
example along with their expected output. The while..loop and for..loop comes under
iterative statements concepts. In second part of the unit, the Jump statements like
pass, continue and break in Programming Language were discussed. The jump
statements are used to alter the program flow. Using break or continue outside a
loop causes an error. Pass statement is used when a statement is required
syntactically but no command or code has to be executed.When the compiler
encounters a break statement then the rest of the statements in the loop are skipped
and the control is unconditionally transferred to the outside the loop.
UNIT SUMMARY
In this section, the learners learned the Jump statements like pass, continue
and break in Programming Language. The jump statements are used to alter the
program flow. Using break or continue outside a loop causes an error. When the
compiler encounters a continue statement then the rest of the statements in the loop
are skipped and the control is unconditionally transferred to the loop-continuation
portion of the nearest enclosing loop. Pass statement is used when a statement is
required syntactically but no command or code has to be executed.
GLOSSARY
Conditional branching statements Statements that helps to jump from one part of
the program to another depending on whether a particular conditions is satisfied or
not.
If-else-if statement Decision control statement that works in the same way as a
normal if statement. It also known as nested if construct.
If-else statement Decision control statement in which first the test expression is
evaluated. If the expression is True, if block is executed and else block is skipped.
Otherwise, if the expression is false, else block is executed and if the block is
ignored.
If-statement Simplest form of decision control statement that is frequently used in
decision making.
2. Write a program to check the largest among the given three numbers
3. Write a Python program to check if the input year is a leap year or not
EXERCISES
QUIZ - ANSWERS
QUIZ - 1 & 2
1. c.Loop Control Flow Statements
2. c.else
3. a.elif
4. c.while
5. 2*i+1
6. d.pass
7. b.break
8. c.continue
9. b.break
10. d.pass
SUGGESTED READINGS
https://www.python.org/about/gettingstarted/
https://www.w3schools.com/python/
https://docs.python.org/3/tutorial/index.html
https://www.geeksforgeeks.org/python-programming-language/
REFERENCES
PYTHON PROGRAMMING
UNIT 3- PYTHON PROGRAMMING
Functions: Function Definition – Function Call – Variable Scope and
its Lifetime-Return Statement. Function Arguments: Required
Arguments, Keyword Arguments, Default Arguments and Variable
Length Arguments- Recursion. Python Strings: String operations-
Immutable Strings - Built-in String Methods and Functions - String
Comparison. Modules: import statement- The Python module – dir()
function – Modules and Namespace – Defining our own modules
Page
Section Topic
No.
UNIT - III
Unit Objectives
Section 3.1 Functions 67
3.1.1 Function Definition 69
3.1.2 Function Call 69
3.1.3 Variable Scope and its Lifetime 70
3.1.4 Return Statement 71
3.1.5 Function Arguments 72
3.1.5.1 Required Arguments 73
3.1.5.2 Keyword Arguments 74
3.1.5.3 Default Arguments 75
3.1.5.4 Variable Length Arguments 76
3.1.6 Recursion 77
Let Us Sum Up
Check Your Progress
Section 3.2 Python Strings 78
3.2.1 String operations 79
3.2.2 Immutable Strings 80
3.2.3 Built-in String Methods and Functions 81
3.2.4 String Comparison 84
Let Us Sum Up
Check Your Progress
3.3 Modules 85
3.3.1 import statement 86
3.3.2 The Python module 86
3.3.3 dir()function 87
3.3.4 Modules and namespace 87
3.3.5 Defining your own module 88
Let Us Sum Up
Check Your Progress
3.4 Unit- Summary 90
3.5 Glossary 90
3.6 Self- Assessment Questions 91
3.7 Exercises 91
3.8 Answers 92
3.9 Suggested Readings 92
3.10 Open Source E-Content Links 92
3.11 References 93
UNIT OBJECTIVES
In this unit, the learners will understand the meaning and scope of functions,
Strings and modules in python programming. It will discuss the way to define a
function / call a function. The various types of arguments supported by function
concept will be discussed. The variable scope and life time which is very important to
keep track is discussed. It also describes the role of return statement in a function. In
Python String place a major role. The way its declared, accessed, formatted, indexed
are also discussed. Finally the role of Module in python will be briefed.
1. Built-in functions – these are the functions which are already defined in the
language. Example print( ), max( ), input( ), etc.
2. User Defined functions- these are the functions that can be created or
defined by the users according to their needs.
3. Anonymous functions
A function can be defined using def statement and giving suitable name to a
function by following the rules of identifiers. The process of defining a function is
called function definition.
Syntax
Even if the function is defined, it can never be executed till the time it is called.
Hence, for using a function, it must be called using function call statement. A function
can be called by its name with set of parenthesis and optional list of arguments.
Syntax
function_name(list_of_arguments)
Example
OUTPUT:
HELLO WORLD …!
Function needs to be defined only once, but it can be called any number of
times by using calling statements. They can not only be called in the same program,
but they can also be called in different programs. Another example shown below is
the program having a function to calculate factorial of a number.
Example
def factorial():
fact=1
n=int(input(“enter a number :”)
for i in range(1, n+1):
fact= fact + i
print(“factorial of “, n “,is “,fact)
factorial()
Output:
Enter a number: 4
Factorial of 4 is 24
Local variables are the variable created within a function’s body or function’s
scope. They cannot be accessed outside the function. Their scope is only
limited to the function in which they are created.
Global variables are the variable created outside any function. Their scope is
global, hence can be used anywhere. Global variables can also be created
within function using keyword global.
A function may or may not have a return[expression] statement. That is, the
return statement is optional. You can assign the function name to a variable After
writing the code statements, the block is ended with a return statement whose syntax
is return [expression].If you want to return more than one value, separate the values
using commas. The default return value is NONE.
Syntax
return [expression]
Example
def factorial(N):
fact=1
for i in range(1, n+1):
fact= fact + i
return(fact)
n=int(input(“enter a number :”)
fact=factorial(n)
print(“factorial of “, n “,is “,fact)
OUTPUT
Enter a number :4
Factorial of 4 is 24
two or more arguments to be passed such as the power function in math module
math.pow(), where we have to pass two arguments, the base and the exponent.
There can be four types of formal arguments using which a function can be
called which are as follows:
1. Required arguments
2. Keyword arguments
3. Default arguments
4. Variable-length arguments
We should send two contentions to the capability() all put together; it will
return a language structure blunder, as seen beneath.
Example
# Defining a function
def function( n1, n2 ):
print(“number 1 is: ”, n1)
print(“number 2 is: ”, n2)
Example
# Defining a function
def function( n1, n2 ):
print(“number 1 is: ”, n1)
print(“number 2 is: ”, n2)
Output:
Example
# defining a function
def function( n1, n2 = 20 ):
print(“number 1 is: “, n1)
print(“number 2 is: “, n2)
# Calling the function and passing only one argument
print( “Passing only one argument” )
function(30)
# Now giving two arguments to the function
print( “Passing two arguments” )
function(50,30)
Output:
number 2 is: 20
Passing two arguments
number 1 is: 50
number 2 is: 30
Example
# Defining a function
def function( *args_list ):
ans = []
for l in args_list:
ans.append( l.upper() )
return ans
# Passing args arguments
object = function('Python', 'Functions', 'tutorial')
print( object )
# defining a function
def function( **kargs_list ):
ans = []
for key, value in kargs_list.items():
ans.append([key, value])
return ans
# Paasing kwargs arguments
object = function(First = ”Python”, Second = ”Functions”, Third = ”Tutorial”)
print(object)
Output:
3.1.6 Recursion
Example
def factorial(x):
“““This is a recursive function to find the factorial of an integer”““
if x == 1:
return 1
else:
return (x * factorial(x-1))
num = 10
print(“The factorial of”, num, “is”, factorial(num))
OUTPUT:
The factorial of 10 is 3628800
Let’s Sum Up
In this section we have seen the role of a function definition in Python
Programming. Functions are self-contained programs that perform some particular
tasks. Once a function is created by the programmer for a specific task, this function
can be called anytime to perform that task. Suppose, we want to perform a task
several times, in such a scenario, rather than writing code for that particular task
repeatedly, we create a function for that task and call it when we want to perform the
task. Each function is given a name, using which we call it. A function may or may
not return a value. There are many built-in functions provided by Python such as
dir(), len(), abs(), etc. Users can also build their own functions, which are called user-
defined functions. If a function, procedure or method calls itself, it is called recursive
4. A function is called using the name with which it was defined earlier, followed
by: a. { } b. () c. <> d. [ ]
Example
Output:
Hello Python
Hello Python
Triple quotes are generally used for
represent the multiline or
docstring.
3.2.1 String Operations
a + b will give
+ Concatenation - Adds values on either side of the operator
HelloPython
[] Slice - Gives the character from the given index a[1] will give e
mark.
Python strings are immutable which means that once created they cannot be
changed. Whenever you try to modify an existing string variable, a new string is
created.
Every object in Python is stored in memory. You can find out whether two
variables are referring to the same object or not by using the id(). The id() returns the
memory address of that object. As both str1 and str2 points to same memory
location, they both point to the same object.
Example
str1=“hello”
print(“str1 is :”,str1)
print(“id of str1 is :”, id(str1))
str2=“world”
print(“str2 is :”,str2)
print(“id of str1 is :”, id(str2))
str1 +=str2
print(“str1 after concatenation is :”,str1)
count(str, beg= 0,end=len(string)) :-Counts how many times str occurs in string
or in a substring of string if starting index beg and ending index end are given.
format(*args, **kwargs) :-This method is used to format the current string value.
format_map(mapping) :-This method is also use to format the current string the
only difference is it uses a mapping object.
isalnum():- Returns true if string has at least 1 character and all characters are
alphanumeric and false otherwise.
isalpha():-eturns true if string has at least 1 character and all characters are
alphabetic and false otherwise.
isascii():-Returns True is all the characters in the string are from the ASCII
character set.
islower():-Returns true if string has at least 1 cased character and all cased
characters are in lowercase and false otherwise.
isupper():-Returns true if string has at least one cased character and all cased
characters are in uppercase and false otherwise.
replace(old, new [, max]) :-Replaces all occurrences of old in string with new or
at most max occurrences if max given.
rsplit():-Splits the string from the end and returns a list of substrings.
title():-Returns “titlecased” version of string, that is, all words begin with
uppercase and the rest are lowercase.
zfill (width) :-Returns original string leftpadded with zeros to a total of width
characters; intended for numbers, zfill() retains any sign given (less one zero).
max(list) :-Returns the max alphabetical character from the string str.
min(list) :-Returns the min alphabetical character from the string str.
We use the == operator to compare two strings. If two strings are equal, the
operator returns True. Otherwise, it returns False. For example,
Example
True
str1 and str2 are not equal. Hence, the result is False.
str1 and str3 are equal. Hence, the result is True.
Let’s Sum Up
Besides numbers, strings are another important data type. Single quotes or
double quotes are used to represent strings. A string in Python can be a series or a
sequence of alphabets, numerals and special characters. Similar to C, the first
character of a string has an index 0. There are many operations that can be
performed on a string. There are several operators such as slice operator ([]) and [:]),
concatenation operator (+), repetition operator (*), etc. Slicing is used to take out a
subset of the string, concatenation is used to combine two or more than two strings
and repetition is used to repeat the same string several times.
7. You cannot multiply a string with a floating point number. (True / False)
8. You can print a string without the print function. (True / False)
9. Single quotes and double quotes ina string cannot used within triple quotes.
(True / False)
Functions and variables that you would like to use even in other programs.
The program in which you want to use functions or variables defined in the module
will simply import that particular module (or .py file). Modules are pre-written pieces
of code that are used to perform common tasks like generating random numbers,
performing mathematical operations, etc.
The basic way to use a module is to add import module_name as the first line
of your program and then writing module_name.var to access functions and values
with the name var in the module.
A module may contain definition for many variables and functions. When you
import a module, you can use any variable or function defined in that module. But if
you want to use only selected variables or functions, then you can use the
from...import statement.
For example, in the aforementioned program you are using only the path
variable in the sys module, so you could have better written from sys import path.
Example
PI =3.141592653589793
To import more than one item from a module, use a comma separated list. For
example, to import the value of pi and sqrt() from the math module you can write,
We have seen that a Python module is a file that contains some definitions
and statements. When a Python file is executed directly, it is considered the
main module of a program.
Main modules are given the special name __main__ and provide the basis for
a complete Python program.
The main module may import any number of other modules which may in turn
import other modules. But the main module of a Python program cannot be
imported into other module
dir() is a built-in function that lists the identifiers defined in a module. These
identifiers may include functions, classes and variables. If no name is specified, the
dir() will return the list of names defined in the current module.
Example
def print_var(x):
print(x)
x=10
print_var(x)
print(dir())
OUTPUT:
10
[‘__builtins__’,’__doc__’,’__name__’,’__package__’,’print_var’,’x’]
Example:
#module1
def repeat_m(x):
return x*3;
#module2
def repeat_m(x):
return x*3;
import module1
import module2
result=repeat_m(10) #ambiguous reference for identifier repeat_m
Advantages of Modules:
Python modules provide all the benefits of modular software design. These
modules provide services and functionality that can be reused in other
programs.
Even the standard library of Python contains a set of modules. It allows you to
logically organize the code so that it becomes easier to understand and use.
Every Python program is a module, that is, every file that you save as .py
extension is a module. Modules should be placed in the same directory as that of
the program in which it is imported. It can also be stored in one of the directories
listed in sys.path.
First write these lines in a file and save the file as mymodule.py
def display():
print(“Hello”)
Then open another file (main.py) and write the lines of code given below.
import mymodule
mymodule.display()
OUTPUT:
Hello
Let Us Sum Up
In this section we have studied the literal constants that we can be used
directly in Programming Language which made so popular to be used in current
upcoming applications by the developer. Python is recommended as first
programming language for beginners. Python is an Example of Dynamically typed
programming language.
12. To import sqrt and cos function from the math module write ____
14. If a particular module is imported more that once, the interpreter will load the
module only once. (True / False)
UNIT SUMMARY
In this section, the learners learned about the functions, which are self-
contained programs that perform some particular tasks. There are many built-in
functions provided by Python such as dir(), len(), abs(), etc., and users can also
make their own functions which are known as user-defined functions. The block of
the function starts with a keyword def after which we write our function name
followed by parentheses. A module is a file that contains some predefined Python
codes. A module can define functions, classes and variables. It is a collection of
related functions grouped together.
Parameters and arguments are the values or expressions that are passed to
the functions between the parentheses. In keyword arguments, the caller recognises
the arguments by the parameter’s names. This type of argument can also be skipped
or can also be out of order. In default arguments, we can assign a value to a
parameter at the time of function definition that will be considered the default value to
that parameter.
GLOSSARY
FUNCTION: Functions are self-contained programs that perform some particular
tasks.
RETURN VALUE: The value returned by the function as output to the caller.
1. What are the benefits of using functions? Also differentiate between function
definition and function calling.
2. What is Scope of a variable? Explain local and global variables with example.
EXERCISES
QUIZ - ANSWERS
1. d.All
2. b.def
3. c.module
4. b.()
5. a.exit a function
6. string
7. True
8. True
9. False
10. False
11. b..py
12. from math import sqrt, cos
13. True
14. True
15. True
SUGGESTED READINGS
https://www.python.org/about/gettingstarted/
https://www.tutorialspoint.com/python/python_literals.htm
https://www.w3schools.com/python/
https://docs.python.org/3/tutorial/index.html
https://www.geeksforgeeks.org/python-programming-language/
REFERENCES
PYTHON PROGRAMMING
UNIT OBJECTIVES
In this unit, learner will explore the various data types supported by Python
which includes List, Tuple and Dictionary. How to create the above three? How to
access the values in it? How to update or delete an element in it? The unit also
discusses the different functions and methods that can be performed on List, Tuple
and Dictionary. Finally the differences between List and Tuple, List and Dictionary
are also discussed.
Lists in Python are ordered and have a definite sequence and the indexing of
a list is done with 0 being the first index. Each element in the list has its definite
place in the list, which allows duplicating of elements in the list, with each element
having its own distinct place and creditability. It is represented by list class.
lst_var=[val1,val2..]
Example
>>>lst1[1,2,3,4,5] >>>lst1=[‘a’,’b’,’c’,’d’]
>>>print(lst1) >>>print(lst2)
[1,2,3,4,5] [‘a’,’b’,’c’,’d’]
>>>lst3=[“Python”, >>>lst4=[‘1’,’ball’,9,34.89]
“Programming”]
>>>print(lst4)
>>>print(lst3)
[‘1’,’ball’,9,34.89]
[“Python”, “Programming”]
List can also be sliced and concatenated. To access values in a lists, square
brackets are used to slice along with the index or indices to get value stored at that
index.
seq=List[start:stop:step]
Example
numlst=[1,2,3,4,5,6,7,8,9,10]
print(“numlist is :”,numlst)
print(“numlst[2:5] =”,numlst[2:5])
print(“numlst[::2] =”,numlst[::2])
print(“numlst[1::3] =”,numlst[1::3])
Output:
numlist is : [1,2,3,4,5,6,7,8,9,10]
numlst[2:5] =[3,4,5]
numlst[::2] = [1,3,5,7,9]
numlst[1::3] =[2,5,8]
Once created, one or more elements of a list can be easily updated by giving
the slice on the left-hand side of the assignment operator. You can also append new
values in the list and remove existing values from the list using the append( ) method
and del statement respectively.
Example:
num_list= [1,2,3,4,5,6,7,8,9,10]
print(“list is:”,num_list)
num_list[5]=100
num_list.append(200)
del num_list[3]
Output:
Example
lst=[1.’a’,”abc”,[10,20,30],5.9]
I=0
while i<(len(lst)):
i+=1
OUTPUT:
List[0]=1
List[1]=a
List[2]=abc
List[3]=[10,20,30]
List[4]=5.9
cmp(list1,list2) It compares the elements of both the lists, list1 and list2.
len(list) It returns the length of the string, i.e., the distance from starting element to
last element.
max(list) It returns the item that has the maximum value in a list.
min(list) It returns the item that has the minimum value in a list.
list.extend(seq) It adds the elements of the sequence at the end of the list.
list.index(item) It returns the index number of the item. If item appears more than
one time, it returns the lowest index number.
list.insert(index,item) It inserts the given item onto the given index number while
the elements in the list take one right shift.
list.reverse() It reverses the position (index number) of the items in the list.
list.sort([func]) It sorts the elements inside the list and uses compare function if
provided
pop Operator If we know the index of the element that we want to delete,
then we can use the pop operator.
Example
list = [10,20,30,40]
a = list.pop(2)
print list
print a
Output
[10,20,40]
30
del Operator The del operator deletes the value on the provided index, but it
does not store the value for further use.
Example
list = [‘w’,‘x’,’y’,’z’]
del list(1)
print list
Output
remove Operator We use the remove operator if we know the item that we
want to remove or delete from the list (but not the index).
Example
list = [10,20,30,40]
list.remove(10)
print list
Output
[20,30,40]
Let’s Sum Up
In this section we have studied the various features of List in Python
Programming Language. How to create a List, access the elements in it, how to
delete or update the elements with the basic operations that can be performed in a
List. Finally discussed the functions and methods that can be performed in a List.
a. * b. , c. ; d. & 19.
a. * b. , c. ; d. &
4. What will be the output of the given code? list = [‘john’, ‘book’, 123, 3.45, 105,
‘good’] >>>print (list[4:])
5. Which of the following functions will give the total length of a list?
Like list, Tuple is another data structure supported by Python. It is very similar
to list but differs in two things.
Second, tuples uses parentheses to define its elements where as list uses
square brackets.
Syntax:
Tup1=(val1,val2,….)
where val (or values) can be an integer, a floating number, a character, or a string.
Examples
print(Tup1)
Output:
print(Tup1)
Output:
print (Tup1)
print(Tup2)
print(Tup3)
print(Tup4)
print(Tup5)
Output:
1,2,3,4,5
“a‟,‟b‟,‟c‟,‟d‟
“abc‟,‟def‟,‟ghi‟
1.2,2.3,3.4,4.5,5.6
1,‟abc‟,2.3,‟d‟
print(“a‟,”bcd”,2,4.6)
Output:
A bcd2 4.6
a,b=10,20
print(a,b)
Output:
10 20
Like strings and lists tuples indices also starts with 0. The operations
performed are slice, concatenate, etc.. To access values in tuple, slice operation is
used along with the index
Example :
1) Tup1=(1,2,3,4,5,6,7,8,9,10)
print(“Tup[3:6]=”,Tup1[3:6])
print(“Tup[:8]=”,Tup1[:4])
print(“Tup[4:]=”,Tup1[4:])
print(“Tup[:]=”,Tup1[:])
Output:
Tup[3:6]=(4,5,6)
Tup[:8]=(1,2,3,4)
Tup[4:]=5,6,7,8,9,10)
Tup[:]=(1,2,3,4,5,6,7,8,9,10)
The tuple values can be accessed using square brackets:
2) tuple =(1,2,3,4,5.5,‟str‟)
print tuple
print tuple[5]
print tuple[1:5
OUTPUT:
1,2,3,4,5.5,‟str‟
‟str‟
2,3,4,5.5
As we all know tuples are immutable objects so we cannot update the values
but we can just extract the values from a tuple to form another tuple.
Example:
1) Tup1=(1,2,3,4,5)
Tup2=(6,7,8,9,10)
Tup3=Tup1+Tup2
print(Tup3)
Output:
(1,2,3,4,5,6,7,8,9,10)
2) Tup1=(1,2,3,4,5)
Tup2=(„sree‟,‟vidya‟,‟ram‟)
Tup3=Tup1+Tup2
print Tup3
Output:
(1,2,3,4,5,‟sree‟,‟vidya‟,‟ram‟)
Example
1) Tup1=(1,2,3,4,5)
del Tup1[3]
print Tup1
Output:
del Tup1[3]
Tup1=(1,2,3,4,5)
del Tup1
print Tup1
Output:
Traceback (most recent call last):
print Tup1;
Note: Note that exception is raised because you are now trying to print a tuple that
has already been deleted.
Like strings and lists, you can also perform operations like concatenation,
repetition, etc. on tuples. The only difference is that a new tuple should be created
when a change is required in an existing tuple.
Length len((1,2,3,4,5,6)) 6
Tup2=(1,2,3,4,5)
print(Tup1>Tup2)
Maximum max(1,3,5,7,9,0) 9
Minimum min(1,3,5,7,9,0) 0
Python allows you to define a tuple inside another tuple. This is called a
nested tuple.
Example
stud=((“Anu”,”Bsc”,89.0),(“Banu”,”BA”,78.0),(”Chandru”,”BCom”,95.0))
for I in stud:
print(i)
Output
(“Anu”,”Bsc”,89.0)
(“Banu”,”BA”,78.0)
(“Chandru”,”BCom”,95.0)
stud=((“Anu”,[93,89,90,91])
Output
Let’s Sum Up
In this section, the learner studied the various features Tuples in Python
Programming Language and how to create a tuple, access the elements in it? , how
to delete or update the elements with the basic operations that can be performed in a
tuple. Finally the section discussed the difference between a List and Tuple.
Syntax:
If there are many keys and values in dictionaries, then we can also write just one
key-value pair on a line to make the code easier to read and understand.
Keys in the dictionary must be unique and be of any immutable data type (like
Strings, numbers, or tuples), there is no strict requirement for uniqueness and
type of values.
Values of a key can be of any type.
Dictionaries are not Sequences, rather they are mappings.
Mappings are collections of objects that are store objects by key instead of by
relative position.
Example:
d= {'roll_no':'18/001','Name:':'Arav','Course':'B.tech'}
print(d)
Output:
Example:
print('d[Name]:',d['Name'])
print('d[course]:',d['Course'])
print('d[roll_no]:',d['roll_no'])
Output:
d[Name]: Arav
d[course]: B.tech
d[roll_no]: 18/001
Syntax
Example:
print('d[Name]:',d['Name'])
print('d[course]:',d['Course'])
print('d[roll_no]:',d['roll_no'])
print('d[marks]:',d['marks'])
Output:
d[Name]: Arav
d[course]: B.tech
d[roll_no]: 18/001
d[marks]: 99
print('d[Name]:',d['Name'])
print('d[course]:',d['Course'])
print('d[roll_no]:',d['roll_no'])
print('d[marks]:',d['marks'])
print('d[course]:',d['Course'])
OUTPUT:
d[Name]: Arav
d[course]: B.tech
d[roll_no]: 18/001
d[marks]: 99
d[course]: BCA
You can delete one or more items using the del keyword. To delete or
remove all the items in just one statement, use the clear () function. Finally, to
remove an entire dictionary from the memory, we can gain use the del statement as
del Dict_name.
syntax
del dictionary_variable[key]
Example:
dict_cubes.pop(3)
dict_cubes.popitem()
dict_cubes.popitem()
dict_cubes
print (dict_cubes)
Output
(1, 1)
(2, 8)
{}
printdict_cubes
Traversing Traversing in dictionary is done on the basis of keys. For this, for
loop is used, which iterates over the keys in the dictionary and prints the
corresponding values using keys.
Example
def print_dict(d):
for c in d:
print c,d[c]
dict1 = {1:’a’,2:’b’,3:’c’,4:’d’}
print_dict(dict1)
OUTPUT:
1a
2b
3c
4d
Membership Using the membership operator (in and not in), we can test
whether a key is in the dictionary or not. We have seen the in operator earlier as well
in the list and the tuple. It takes an input key and finds the key in the dictionary. If the
key is found, then it returns True, otherwise, False.
Example
print(3 in cubes)
print(10 in cubes)
Output:
True
True
False
1. all(dict) It is a Boolean type function, which returns True if all keys of dictionary
are true (or the dictionary is empty).
2. any(dict) It is also a Boolean type function, which returns True if any key of the
dictionary is true. It returns false if the dictionary is empty.
3. len(dict) It returns the number of items (length) in the dictionary.
4. cmp(dict1,dict2) It compares the items of two dictionaries.
5. sorted(dict) It returns the sorted list of keys.
6. str(dict) It produces a printable string representation of the dictionary.
7. dict.clear() It deletes all the items in a dictionary at once.
8. dict.copy() It returns a copy of the dictionary.
9. dict.fromkeys() It creates a new dictionary with keys from sequence and values
set to value.
10. dict.get(key, default=None) For key key, returns value or default if key not in
dictionary.
11. dict.has_key(key) It finds the key in dictionary; returns True if found and false
otherwise.
12. dict.items() It returns a list of entire key: value pair of dictionary.
First, a list is an ordered set of items. But, a dictionary is a data structure that
is used for matching one item (key) with another (value).
Second, in lists, you can use indexing to access a particular item. But, these
indexes should be a number. In dictionaries, you can use any type(immutable) of
value as an index.
Third, lists are used to look up a value whereas a dictionary is used to take
one value and look up another value. For this reason, dictionary is also known as a
lookup table.
Fourth, the key-Value pair may not be displayed in the order in which it was
specified while defining the dictionary. This is because Python uses complex
algorithms(called hashing) to provide fast access to the items stored in the
dictionary. This also makes dictionary preferable to use over a list.
Let’s Sum Up
In this section we have studied the various features Dictionary in Python
Programming Language. How to create a Dictionary, access the elements in it, how
to delete or update the elements with the basic operations that can be performed in a
UNIT SUMMARY
In this unit, the learner had learned about list which is a collection of items or
elements; the sequence of data in a list is ordered. The elements or items in a list
can be accessed by their positions, i.e., indices. Lists are mutable which means that
we can change the value of any element inside the list at any point of time. Tuples
are the sequences of different types of values. Tuples are immutable and thus the
elements or values cannot be modified. A dictionary is a mapping between some set
of keys and values. Each key is associated with a value. The mapping of a key and
value is called a key-value pair and together they form one item or element. The
values in a dictionary are not unique and can be duplicated, but the keys in the
dictionary are unique. The difference between the accessing methods of dictionary is
that when the key is not found in dictionary, it returns none instead of KeyError.
Dictionaries are mutable and thus the elements or values can be modified.
GLOSSARY
LIST: It is a series or a sequence of different data items.
OBJECT: It is something a variable can refer to. An object has a type and value.
TUPLE: Tuples, just like lists, are the sequence or series of different types of values
that are separated by commas (,).
CONCATENATION: This operator works in tuples in the same way as in lists. This
operator concatenates two tuples. This is done by the + operator in Python.
REPETITION: This operator repeats the tuples a given number of times. Repetition
is performed by * operator.
in OPERATOR: This operator tells the user whether the given element exists in the
tuple or not. It gives a Boolean output, i.e., TRUE or FALSE.
ITERATION: Iteration can be done in tuples using for loop. It helps in traversing the
tuple.
5. What are the different methods used in deleting elements from dictionary?
EXERCISES
1. How can we add an element in the list? Write a program to insert 32 to the fourth
position in the given list [1, 4, 23, 56, 90].
3. Consider the tuple (1,3,5,7,9,2,4,6,8,10). Write a program to print half its values
in one line and the other half in the next line.
QUIZ - ANSWERS
1. b,
2. a.*
3. b. list.sort([func])
4. [105,’good’]
5. b.len(list)
6. b.list
7. d.()
8. (7,8,9)
9. a.john
10. c. tuple[4] = 20
11. b.dictionary
12. a.{}
13. d.numbers or strings
14. c.[]
15. a.keys and values
SUGGESTED READINGS
1. Yashavant Kanetkar and Aditya Kanetkar, “Let us Python Solutions”, -bpb
publications, 6th Edition, 2023
REFERENCES
1. Reema Thareja,”Python Pogramming using Problem Solving approach”,
Oxford Higher Education,
PYTHON PROGRAMMING
UNIT OBJECTIVES
In this unit, learners will have a elaborate understanding of File concepts,
various file types in Python. How to write the contents into a file using write or
writeline method. Similarly how to read the contents from the file using read or
readline method. Before doing any operations in a file it has to be opened which has
various modes like read, write, append, binary or text, etc., Once the job gets
completed it has to be closed. While reading a file user can navigate to a particular
location in a file. The way to rename or delete a file is also discussed.
A file is basically used because real life applications involve large amount of
data and in such situations console oriented I/O operations pose two major
problems:
Second, when doing I/O using terminal, the entire data is lost when either the
program is terminated or computer is turned off. Therefore, it becomes
Another important thing is that when a text file is used, there are actually two
representations of data- internal or external. For example, an integer value will be
represented as a number that occupies 2 or 4 bytes of memory internally but
externally the integer value will be represented as a string of characters representing
its decimal or hexadecimal value.
Note: In a text file, each line of data ends with a newline character. Each file
ends with a special character called end-of-file (EOF) Marker.
Binary Files
A binary file is a file which may contain any type of data, encoded in binary
form for computer storage and processing purposes. It includes files such as word
processing documents, PDFs, images, spreadsheets, videos, zip files and other
executable programs. Like a text file, a binary file is a collection of bytes. A binary
file is also referred to as a character stream with following two essential differences.
A binary file does not require any special processing of the data and each
byte of data is transferred to or from the disk unprocessed. Python places no
constructs on the file, and it may be read from, or written to, in any manner the
programmer wants. While text files can be processed sequentially, binary files, on
the other hand, can be either processed sequentially or randomly depending on the
needs of the application.
Note: Binary files store data in the internal representation format. Therefore,
an integer value will be stored in binary form as 2 byte value. The same format is
used to store data in memory as well as in files. Like Text files, Binary files also ends
with an EOF.
When we want to read from or write to a file we need to open it first. When we
are done, it needs to be closed, so that resources that are tied with the file are freed.
Python has many in-built functions and methods to manipulate files. Hence, in
Python, a file operation takes place in the following order
1. Open a file
Before reading from or writing to a file, you must first open it using Python’s
built-in open() function. This function creates a file object, which will be used to
invoke methods associated with it.
Syntax
file_name is a string value that specifies name of the file that you want to
access
access_mode indicates the mode in which the file has to be opened, i.e.
read, write, append, etc. Access mode is an optional parameter and the
default file access mode is read(r).
EXAMPLE
file=open(“file1.txt”,”rb”)
print(file)
OUTPUT
Access modes
Python supports the following access modes for opening a file those are:
Once a file is successfully opened, a file object is returned. Using this file
object, you can easily access different type of information related to that file. This
information can be obtained by reading values of specific attributes of the file. The
Following table shows list attributes related to file object.
Example
# open a file
f = open(“C:/Python27/test.txt”,”wb”)
print (f.name)
print (f.closed)
print (f.mode)
print (f.softspace)
print (f.closed)
Output :
C:/Python27/test.txt
False
Wb
True
Closing A File
The close() method is used to close the file object. Once a file object is
closed, you cannot further read from or write into the file associated with the file
object. While closing the file object the close() flushes any unwritten information.
Although, Python automatically closes a file when the reference object of a file is
reassigned to another file, but as a good programming habit you should always
explicitly use the close() method to close a file.
Syntax:
fileObj.close()
The close() method frees up any system resources such as file descriptors,
file locks, etc. that are associated with the file. Once the file is closed using the
close() method, any attempt to use the file object will result in an error.
file = open('File1.txt','wb')
print('File is closed:',file.closed)
file.close()
print('File is closed',file.closed)
print(file.read())
Output:
print(file.read())
io.UnsupportedOperation: read
The read() and write() are used to read data from file and write data to file
respectively. Both functions are used to manipulate data through files.
Syntax
fileObj.write(string)
file=open('data.txt','w')
file.close()
Output:
writeline() method:
file=open('data.txt','w')
file.writelines(lines)
file.close()
Output:
Once you have stored some data in a file,you can always open that file again
to write more data or append data to it. To append a file, you must open it using „a‟
or „ab‟ mode depending on whether it is text file or binary file. Note that if you open a
file with „w‟ or „wb‟ mode and then start writing data into it, then the existing contents
would be overwritten.
file=open('data.txt','a')
file.close()
Output:
data.txt
The read() method is used to read a string from an already opened file. As
said before, the string can include, alphabets, numbers, characters or other symbols.
Syntax
fileObj.read([count])
The read() method starts reading from the beginning of the file and if count is
missing or has a negative value then, it reads the entire contents of the file (i.e., till
the end of file).
file=open('data.txt','r')
print(file.read(8))
file.close()
Output:
hellocse
file=open('data.txt','r')
print(line)
file.close()
Output:
readline() Method
It is used to read single line from the file. This method returns an empty string
when end of the file has been reached.
file=open('data.txt','r')
print('firtsline:',file.readline())
print('second line:',file.readline())
print('third line:',file.readline())
file.close()
Output:
third line:
readlines() Method
file=open('data.txt','r')
print(file.readlines())
file.close()
Output:
list() Method
list() method is also used to display entire contents of the file. you need to
pass the file object as an argument to the list() method.
Example: display the contents of the file data.txt using the list() method
file=open('data.txt','r')
print(list(file))
file.close()
Output:
It is good programming habit to use the with keyword when working with file
objects. This has the advantage that the file is properly closed after it is used even if
an error occurs during read or write operation or even when you forget to explicitly
close the file. When you open a file for reading, or writing, the file is searched in the
current directory. If the file exists somewhere else then you need to specify the path
of the file.
Example:
Python allows you to read line(s) from a file and splits the line (treated as a
string) based on a character. By default, this character is space but you can even
specify any other character to split words in the string.
Example: Program to split the line into series of words and use space to
perform the split operation
line=file.readline()
words=line.split()
print(words)
Output:
With every file, the file management system associates a pointer often known
as file pointer that facilitates the movement across the file for reading and/ or writing
data. The file pointer specifies a location from where the current read or write
operation is initiated. Once the read/write operation is completed, the pointer is
automatically updated. Python has various methods that tells or sets the position of
the file pointer.
For example, the tell() method tells the current position within the file at which
the next read or write operation will occur. It is specified as number of bytes from the
beginning of the file. When you just open a file for reading, the file pointer is
positioned at location 0, which is the beginning of the file.
Syntax
seek(offset[, from])
Example: Program that tells and sets the position of file pointer
File1.txt
Hello All,
file=open(“File1.txt”,”rb”)
print(file.read(10)
file.seek(3,1)
print(file.read())
file.close()
OUTPUT:
Hello All,
The os module in Python has various methods that can be used to perform
fileprocessing operations like renaming and deleting files. To use the methods
defined in the os module, you should first import it in your program then call any
related functions.
rename() Method: The rename() method takes two arguments, the current
filename and the new filename.
Syntax
os.rename(old_file_name, new_file_name)
remove() Method: This method can be used to delete file(s). The method
takes a filename (name of the file to be deleted) as an argument and deletes
that file.
Syntax
os.remove(file_name)
import os
os.rename(“File1.txt”,”students.txt”)
print(“File Renamed”)
Output:
File Renamed
import os
os.remove(“File1.txt”)
print(“File Deleted”)
Output:
File Deleted
Let’s Sum Up
In this section, the user learned the concept of File. How to read a text file
character by character or line by line. The text content can be written into text file
using write() or writeline() method. Although file I/O operations is almost same as
I/O, the only difference is that when doing file I/O, the user must specify the name of
the file from which data should be read / written along with mode. The default mode
is read. Using append() the content can be added to the existing file. The split()
method used to split the words in a file. The file pointer can be moved to a particular
location using seek() function and the current location in a file can be tracked using
tell() method.
a. f = open(“xyz.txt”,’r’) b. f = open(“xyz.txt,’w’)
c. f = open(“xyz.txt,’a’) d. f = open(“xyz.txt”)
5. At what position will the file pointer be placed whenever we open a file for
reading or writing?
7. Whenever we open a file for appending, at what position will the file pointer be
placed?
a. When a file is opened for reading, if the file does not exist, an empty file will
be opened.
b. When a file is opened for writing, overwrites the file if the file exists.
c. When a file is opened for writing, if the file does not exist, creates a new file
for writing.
d. When a file is opened for reading, if the file does not exist, an error occurs.
9. Which of the following statements is correct while using ‘a+’ mode for opening
a file?
UNIT SUMMARY
GLOSSARY
File handle An object that allows you to manipulate / read/ write/ close the
file.
File Path A sequence of directory names that specifics the exact location of a
file.
Non-volatile memory Memory that can store data even when the power
supply to the computer system is switched off.
Text file A file having printable characters organized into lines separated by
newline characters.
Volatile memory Memory that loses data as soon as the computer system is
switched off. RAM is an example of volatile memory.
1. What are the different access modes in which you can open a file?
EXERCISES
1. Write a program that tells and set the position of the file pointer.
2. Write a program that accepts filename as input, open the file and count the
number of times a character appears in the file.
3. Write a program that reads data from a file and calculates the percentage of
vowels and consonants in the file.
4. Write a program that reads a file and prints only those lines that has the word
‘print’.
5. Write a program that has several lines. Each line begins with a line number.
Read this file line by line and copy the line in another file but do not copy the
numbers.
ANSWERS
1. b. open()
2. d. Handle
3. c. Text
4. a. f = open(“xyz.txt”,’r’)
5. b. Beginning
6. c. read (r)
7. b. Beginning
8. a. When a file is opened for reading, if the file does not exist, an empty file will
be opened
9. c. Opens a file for both appending and reading
10. d. fileObject.close()
SUGGESTED READINGS
https://www.python.org/about/gettingstarted/
https://www.w3schools.com/python/
https://docs.python.org/3/tutorial/index.html
https://www.geeksforgeeks.org/python-programming-language/
REFERENCES