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

Python Complete Notes

Download as pdf or txt
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 202

Lecture Notes-1 Python Programming

Brief history and need for Python Programming


• Python was created by Guido Van Rossum in 1991.
• Python is a general-purpose programming language which helps in automating the
tasks.
• It is ease and simple.
• It consists of simplified syntaxes and it executes very fast.
• It is an object oriented programming language
Features of Python

• Readable: Syntax is similar to English and so the language is readable.


• Easy to learn: Python is expressive language and thus it is easy to learn.
• Cross-Platform: Python can run on different operating systems such as Windows,
Mac, Linux, etc.
• Open Source: This is an open-source language and free to all.
• Large Standard library: Python has a very big library of pre-defined functions.
• Free: Python is freely available to use over your applications.
• Supports Exception Handling: Python has an advanced feature of exception handling.
• Advanced Features: Python supports many advanced features.
• Automatic Memory Management: Python supports this feature which automatically
allocates and free the memory whenever used.

Notes Prepared by : Dr V Prasad, Associate Professor, Dept of CSE, GMRIT


Need for Python Programming
• It helps Software Development
• It helps in Web Application Development
• It helps in Mathematics
• It helps in Script Writing
• It is used to create web applications at server side.
• It is used in simplifying the web flows using inbuilt functions.
Applications of Python
• Web Applications ( Web Site Building )
• GUI Applications ( Graphical User Interface )
• Stand Alone System Applications ( Develop Programs / Codes )
• Console Based Applications ( Command Line Shell Projects )
• Software Development
• Scientific and Numeric Applications
• Business Applications
• Audio and Video Enabled System Applications
• CAD and 3D Applications
• Enterprise Applications
Python deals with Values and Variables
• Numeric Values
• Strings
• Variables
• Assignments
• Identifiers
• Reserved Words
Running Python Scripts ( Simple and Sample Programs)
The Python shell is applicable in two modes a) Interactive Shell and Command Line
Interactive Shell always appears in the screen of web interface, whereas the command line
appears as a stand alone computer terminal
Step 1: Open a New “.py” Document and Write your Program Code
The extension of a python program is given as”.py”.
print("This is a simple Python program for Section J")
Step 2: Save the Python Program
Step 3: Run the Python Program, Thus the program undergoes Compilation and produces the
output.
Output: This is a simple Python program for Section J
The shell executes the python statement in three steps

Notes Prepared by : Dr V Prasad, Associate Professor, Dept of CSE, GMRIT


a) Read the input variable (Read)
b) Evaluate the variable content and process ( Eval )
c) Display the values ( Print )
Identifiers and Statements
Numeric values
print(4) // Output: Displays 4 on the Screen
19 Output: 19 // Represented to be a Number
Strings
“19” Output: ‘19’ // Represented to be a string
‘19’ Output: ‘19’ // Represented to be a String
Note: Single Quote and Double Quotes are delimiters for Strings
Program to Illustrate Indentation
'Prasad'
"Prasad is a Good Boy"
'Prasad Teaches J Section Python'
Output:

Displays and Indentation error as shown below because of the extra space given in the third line

File "<ipython-input-12-faeba1f3783b>", line 3


'Prasad Teaches J Section Python'
^
IndentationError: unexpected indent

Note: Besides the Three Errors Syntax Errors, Logical Errors and Exception Errors, Python
undergoes Indentation Error which we normally face while we encounter loops.
>>> 3 + 4
7
>>> 1 + 2 + 4 + 10 + 3
20
>>> print(1 + 2 + 4 + 10 + 3)
20
Running Simple and Sample Programs:
Write a python code to display your name
Program:
#To display your name
name=input("enter your name:")

Notes Prepared by : Dr V Prasad, Associate Professor, Dept of CSE, GMRIT


print("your name is",name)
Output:
enter your name:ramu
your name is ramu
Write a python code to implement addition of two numbers
Program:
#Addition of two numbers
a=int(input("enter number1:"))
b=int(input("enter number2:"))
print("sum of numbers is",a+b)
Output:
enter number1:5
enter number2:8
sum of numbers is 13
Write a python code to implement multiplication of three numbers
Program:
#Multiplication of three numbers
a=int(input("enter number1:"))
b=int(input("enter number2:"))
c=int(input("enter number3:"))
print("Product of numbers is",a*b*c)
Output:
enter number1:20
enter number2:30
enter number3:40
Product of numbers is 24000

Write a python code to display your name in reverse order


Program:
#Reverse of a name

Notes Prepared by : Dr V Prasad, Associate Professor, Dept of CSE, GMRIT


name=input("enter your name:")
print("reverse of your name is",name[::-1])
Output:
enter your name:ramu
reverse of your name is umar
Note: The slice statement [::-1] means start at the end of the string and end at position 0, move
with the step -1, negative one, which means one step backwards.

***

Notes Prepared by : Dr V Prasad, Associate Professor, Dept of CSE, GMRIT


Lecture Notes-2 Python Programming

Identifiers, Statements, Variables, Keywords

Python Keywords

Keywords are the reserved words in Python where the meaning cannot be changed.

Keywords: False, await, else, import, pass, none, break, except, in ,raise, True, class, finally,
is, return, and, continue, for, lambda, try, as, def, from, nonlocal, while, assert, del, global,
not, with, async, elif, if, or and yield.

Python Identifiers
An identifier is a name given to entities(objects) like class, functions, variables, etc. It helps to
differentiate one entity from another.

Rules for writing identifiers


1. Identifiers can be a combination of letters in lowercase (a to z) or uppercase (A to Z)
or digits (0 to 9) or an underscore _.
Example: myClass
var_1
print_this_to_screen, all are valid example.
2. An identifier cannot start with a digit.
Example: 1variable is invalid, but variable1 is a valid name.
3. Keywords cannot be used as identifiers.
Example: global = 1
4. We cannot use special symbols like !, @, #, $, % etc. in our identifier.
Example: a@ = 0
5. An identifier can be of any length.
6. Python is case sensitive
Example: Prasad and prasad, both are not same
7. Multiple name in a variable could be underscore
Example: V Prasad ( Not Valid )
V_Prasad ( Valid )

Notes Prepared by : Dr V Prasad, Associate Professor, Dept of CSE, GMRIT


Python Variables
A variable is a named location used to store data in the memory.
Example: number = 10
Created a variable named number and assigned the value 10 to the variable.
Numbers and variables can be replaced as and when needed
Example:
number = 10
number = 1.1
Initially, the value of number was 10. Later, it was changed to 1.1
Assigning values to Variables in Python
As you can see from the above example, you can use the assignment operator = to assign a
value to a variable.
Example:
Declaring and assigning value to a variable
website = "apple.com"
print(website)
Note: Python is a type-inferred language, so you don't have to explicitly define the variable
type. It automatically knows that apple.com is a string and declares the website variable as a
string.

Changing the value of a variable

website = "apple.com"

print(website)

# assigning a new value to website

website = "programiz.com"

print(website)

Output:

apple.com

programiz.com

Notes Prepared by : Dr V Prasad, Associate Professor, Dept of CSE, GMRIT


Assigning multiple values to multiple variables

a, b, c = 5, 3.2, "Hello"

print (a)

print (b)

print (c)

Assign the same value to multiple variables

x = y = z = "same"

print (x)

print (y)

print (z)

Statement

A statement is an instruction that a Python interpreter can execute. Python statement ends
with the token NEWLINE character. It means each line in a Python script is a statement.

Example: a = 10 is an assignment statement. where a is a variable name and 10 is its value.


There are other kinds of statements such as if statement, for statement, while statement, etc.,

There are mainly four types of statements in Python,

• Print statements,
• Assignment statements,
• Conditional statements,
• Looping statements.

Python Program for Statement Executions

# statement 1

print('Hello')

# statement 2

x = 20

Notes Prepared by : Dr V Prasad, Associate Professor, Dept of CSE, GMRIT


# statement 3

print(x)

Output: Hello

20

Add multiple statements on a single line separated by semicolons, as follows

# two statements in a single

l = 10; b = 5

# statement 3

print('Area of rectangle:', l * b)

# Output Area of rectangle: 50

Multi-Line Statements

Python statement ends with the token NEWLINE character. But we can extend the statement
over multiple lines using line continuation character (\). This is known as an explicit
continuation.

addition = 10 + 20 + \

30 + 40 + \

50 + 60 + 70

print(addition)

# Output: 280

More Python Statements in Brief

• Multi-Line Statements
• Python Compound Statements
• Simple Statements
• Expression statements
• The pass statement
• The del statement

Notes Prepared by : Dr V Prasad, Associate Professor, Dept of CSE, GMRIT


• The return statement
• The import statement
• The continue and break statement

***

Notes Prepared by : Dr V Prasad, Associate Professor, Dept of CSE, GMRIT


Lecture Notes-3 Python Programming

Input Output Statements, Indentation, Command Line Arguments

Input Output Statements

Input : Any information or data sent to the computer from the user through the keyboard is
called input.

Output: The information produced by the computer to the user is called output. Python
provides us with the two inbuilt functions as input() and output().

Syntax: input(prompt_message);

Note: The python will automatically identify whether the user entered a string, number, or list;
Syntax: print(), normally used to print the output.

Example 1: Method 1 to represent Input() and Output() statements

x=input("Enter First number:")

y=input("Enter Second Number:")

i=int(x)

j=int(y)

print("The Sum:", i+j)

Example 2: Method 2 to represent Input() and Output() statements

x=int(input("Enter Fisrt number:"))

y=int(input("Enter Second Number:"))

print("The Sum:", i+j)

Output for Example 1 & 2:

Enter Fisrt number: 20

Enter Second Number: 30

Notes Prepared by : Dr V Prasad, Associate Professor, Dept of CSE, GMRIT


The Sum: 50

Example 3: Write a Python Program to read the employee details and print the same

eno=int(input("Enter the Emplyoyee number:"))

ename=input("Enter the Employee name:")

esal=float(input("Enter the employee salary:"))

eaddr=input("Enter the employee address:")

married=bool(input("Is employee married?[True|False]:"))

print("Display the Data of the Employee")

print("Emplyoyee number:", eno)

print("Employee name:", ename)

print("Employee salary:", esal)

print(" Employee address:", eaddr)

print("Employee married?:", married)

Output:

Enter the Emplyoyee number: 51530

Enter the Employee name: V Prasad

Enter the employee salary: 80000

Enter the employee address: Rajam, Vizianagaram

Is employee married?[True|False]:True

Display the Data of the Employee

Emplyoyee number: 51530

Employee name: V Prasad

Employee salary: 80000

Employee address: Rajam, Vizianagaram

Notes Prepared by : Dr V Prasad, Associate Professor, Dept of CSE, GMRIT


Employee married: True

Indentation

Python uses indentation to indicate a block of code.Indentation refers to the spaces at the
beginning of a code line.

Example 1:

if 5 > 2:

print("Five is greater than two!")

Output:

Five is greater than two!

Example 2:

if 5 > 2:

print("Five is greater than two!")

Output:

print("Five is greater than two!")

IndentationError: expected an indented block

Example 3:

if 5 > 2:

print("Five is greater than two!")

if 5 > 2:

print("Five is greater than two!")

Output:

Five is greater than two!

Notes Prepared by : Dr V Prasad, Associate Professor, Dept of CSE, GMRIT


Five is greater than two!

Example 4:

if 5 > 2:

print("Five is greater than two!")

print("Five is greater than two!")

Output:

print("Five is greater than two!")

IndentationError: unexpected indent

Example 5:

a = 33

b = 200

if b > a:

print("b is greater than a")

Output:

b is greater than a

Example 6:

a = 33

b = 200

if b > a:

print("b is greater than a")

Output:

# you will get an error

Notes Prepared by : Dr V Prasad, Associate Professor, Dept of CSE, GMRIT


Command Line Arguments

The arguments that are given after the name of the program in the command line shell of the
operating system are known as Command Line Arguments.

Python provides various ways of dealing with these types of arguments. The three most
common are:

• Using sys.argv
• Using getopt module
• Using argparse module

Using sys.argv

The sys module provides functions and variables used to manipulate different parts of the
Python runtime environment. This module provides access to some variables used or
maintained by the interpreter and to functions that interact strongly with the interpreter.

Using getopt module

Python getopt module is similar to the getopt() function of C. Unlike sys module getopt
module extends the separation of the input string by parameter validation. It allows both
short, and long options including a value assignment. However, this module requires the use
of the sys module to process input data properly. To use getopt module, it is required to
remove the first element from the list of command-line arguments.

Using argparse module

Using argparse module is a better option than the above two options as it provides a lot of
options such as positional arguments, default value for arguments, help message, specifying
data type of argument etc.

Note: As a default optional argument, it includes -h, along with its long version –help.

***

Notes Prepared by : Dr V Prasad, Associate Professor, Dept of CSE, GMRIT


Lecture Notes-4 Python Programming
Types: Integer and String Values, Boolean
Python supports a number of numeric and nonnumeric values. In particular, Python programs
can use integer values. The Python statement “print(4)” prints the value 4. The value 4 is an
example of an integer expression. Python supports other types of expressions besides integer
expressions. An expression is a basic building block of a Python statement. The number 4 by
itself is not a complete Python statement and, therefore, cannot be a program. The interpreter,
however, can evaluate a Python expression. You may type the enter 4 directly into the
interactive interpreter shell:

The interactive shell attempts to evaluate both expressions and statements. In this case, the
expression 4 evaluates to 4. The shell executes what is commonly called the read, eval, print
loop. This means the interactive shell’s sole activity consists of
1. reading the text entered by the user,
2. attempting to evaluate the user’s input in the context of what the user has entered up that
point, and
3. printing its evaluation of the user’s input.
If the user enters a 4, the shell interprets it as a 4. If the user enters x = 10, a statement has no
overall value itself, the shell prints nothing. If the user then enters x, the shell prints the
evaluation of x, which is 10. If the user next enters y, the shell reports a error because y has
not been defined in a previous interaction. Python uses the + symbol with integers to perform
normal arithmetic addition, so the interactive shell can serve as a handy adding machine:

The expression "19" is an example of a string value. A string is a sequence of characters.


Strings most often contain nonnumeric characters:

Python recognizes both single quotes (') and double quotes (") as valid ways to delimit a
string value. The word delimit means to determine the boundaries or limits of something. The
left ' symbol determines the beginning of a string, and the right ' symbol that follows specifies
the end of the string. If a single quote marks the beginning of a string value, a single quote
must delimit the end of the string. Similarly, the double quotes, if used instead, must appear

Notes Prepared by: Ms. Santhoshini Sahu, Assistant Professor, Dept of CSE, GMRIT
in pairs. You may not mix the two kinds of quotation marks when used to delimit a particular
string, as the following interactive sequence shows:

The interpreter’s output always uses single quotes, but it accepts either single or double
quotes as valid input. Consider the following interaction sequence:

It is important to note that the expressions 4 and '4' are different. One is an integer expression
and the other is a string expression. All expressions in Python have a type. The type of an
expression indicates the kind of expression it is. An expression’s type is sometimes denoted
as its class. At this point we have considered only integers and strings. The built in type
function reveals the type of any Python expression:

Python associates the type name int with integer expressions and str with string expressions.
The built-in int function creates an actual integer object from a string that looks like an
integer, and the str function creates a string object from the digits that make up an integer:

The expression str(4) evaluates to the string value '4', and int('5') evaluates to the integer
value 5. The int function applied to an integer evaluates simply to the value of the integer

Notes Prepared by: Ms. Santhoshini Sahu, Assistant Professor, Dept of CSE, GMRIT
itself, and similarly str applied to a string results in the same value as the original string. Any
integer has a string representation, but not all strings have an integer equivalent:

In Python, neither wow nor 3.4 represent valid integer expressions. In short, if the contents of
the string (the characters that make it up) look like a valid integer number, you safely can
apply the int function to produce the represented integer.
The plus operator (+) works differently for strings; consider:

The plus operator splices two strings together in a process known as concatenation. Mixing
the two types directly is not allowed:

but the int and str functions can help:


The type function can determine the type of the most complicated expressions:

Notes Prepared by: Ms. Santhoshini Sahu, Assistant Professor, Dept of CSE, GMRIT
Boolean Expressions
Arithmetic expressions evaluate to numeric values; a Boolean expression, sometimes called a
predicate, may have only one of two possible values: false or true. The term Boolean comes
from the name of the British mathematician George Boole. A branch of discrete mathematics
called Boolean algebra is dedicated to the study of the properties and the manipulation of
logical expressions. The simplest Boolean expressions in Python are True and False. In a
Python interactive shell we see:

bool is the name of the class representing Python’s Boolean expressions.

Notes Prepared by: Ms. Santhoshini Sahu, Assistant Professor, Dept of CSE, GMRIT
An expression like 10 < 20 is legal but of little use, since 10 < 20 is always true; the
expression True is equivalent, simpler, and less likely to confuse human readers. Since
variables can change their values during a program’s execution, Boolean expressions are
most useful when their truth values depend on the values of one or more variables. The first
input in the shell binds the variable x to the value 10. The other expressions experiment with
the relational operators. Exactly matching their mathematical representations, the following
expressions all are equivalent:
• x < 10
• 10 > x
• !(x >= 10)
• !(10 <= x)
The relational operators are binary operators and are all left associative. They all have a lower
precedence than any of the arithmetic operators; therefore, Python evaluates the expression
x + 2 < y / 10
as if parentheses were placed as so:
(x + 2) < (y / 10)
***

Notes Prepared by: Ms. Santhoshini Sahu, Assistant Professor, Dept of CSE, GMRIT
Lecture Notes-5 Python Programming
Operators
Python language supports the following types of operators.
• Arithmetic Operators
• Comparison (Relational) Operators
• Assignment Operators
• Logical Operators
• Bitwise Operators
• Membership Operators
• Identity Operators
Arithmetic Operators:
Arithmetic Operators some basic arithmetic operators are +,-,*,/,%,**, and //. You can apply
these operators on numbers as well as variables to perform corresponding operations.

Example:

a=21
b=10
OUTPUT
print("Addition is ",a+b)
print("Subtraction is=",a-b)
print("Multiplication is=",a*b)
print("Modulus is=",a%b)
a=2
b=3
print("Power value is=",a**b)
a=10
b=4
print("Floor Division is=",a//b)

Notes Prepared by: Ms. Santhoshini Sahu, Assistant Professor, Dept of CSE, GMRIT
Comparison (Relational) Operators:
These operators compare the values on either sides of them and decide the relation among
them. They are also called Relational operators. Assume variable a holds 10 and variable b
holds 20, then:

Example:

a=10
b=30
if a<b:
print("b is big") OUTPUT
elif a>b:
print("a is big")
else:
print("both are equal")

Notes Prepared by: Ms. Santhoshini Sahu, Assistant Professor, Dept of CSE, GMRIT
Assignment Operators:
Python Assignment operator is used for assigning the value of right operand to the left
operand.

Example:

a=20
b=10
c=a+b
print(c)
c+=a
print("value of c+=a is:",c)
c-=a
print("value of c-=a is:",c)
c*=a
print("value of c*=a is:",c)
c/=a OUTPUT
print("value of c/=a is:",c)
c%=a
print("value of c%=a is:",c)
c**=a
print("value of c**=a is:",c)
c//=a
print("value of c//=a is:",c)

Notes Prepared by: Ms. Santhoshini Sahu, Assistant Professor, Dept of CSE, GMRIT
Logical operator
Logical operators in Python are used for conditional statements are true or false. Logical
operators in Python are AND, OR and NOT. For logical operators following condition are
applied.
• For AND operator – It returns TRUE if both the operands (right side and left side) are
true.
• For OR operator- It returns TRUE if either of the operand (right side or left side) is
true.
• For NOT operator- returns TRUE if operand is false.
Example:

a = True
b = False OUTPUT
print(('a AND b is',a and b))
print(('a OR b is',a or b))
print(('NOT a is',not a))

Notes Prepared by: Ms. Santhoshini Sahu, Assistant Professor, Dept of CSE, GMRIT
Lecture Notes-6 Python Programming
Operators
Bitwise Operators:
Bitwise operator works on bits and performs bit by bit operation.
Assume if a = 60; and b = 13;
Now in binary format they will be as follows:

a = 0011 1100 a = 0011 1100 a = 0011 1100 a = 0011 1100


b = 0000 1101 b = 0000 1101 b = 0000 1101 --------------------
-------------------- -------------------- -------------------- ~a = 1100 0011
a&b = 0000 1100 a|b = 0011 1101 a^b = 0011 0001

There are following Bitwise operators supported by Python language.

Example:

Notes Prepared by: Ms. Santhoshini Sahu, Assistant Professor, Dept of CSE, GMRIT
a=60
b=13
c=a&b
print("a&b=",c) Output:
c=a|b
print("a|b=",c)
c=a^b
print("a^b=",c)
c=~a
print("~a=",c)
c=a<<2
print("a<<2=",c)
c=a>>2
print("a>>2=",c)

Membership Operators:
Membership operators are operators used to validate the membership of a value. It tests for
membership in a sequence, such as strings, lists, or tuples. There are two membership
operators.
• In Operator
• Not in Operator
in operator:
The ‘in’ operator is used to check if a value exists in a sequence or not. Evaluates to true if it
finds a variable in the specified sequence and false otherwise.

list1=[1,2,3,4,5] OUTPUT:
list2=[6,7,8,9]
for item in list1:
if item in list2:
print("overlapping")
else:
print("not overlapping")

‘not in’ operator:


Evaluates to true if it does not finds a variable in the specified sequence and false otherwise.
Example:

Notes Prepared by: Ms. Santhoshini Sahu, Assistant Professor, Dept of CSE, GMRIT
x = 24
y = 20
list = [10, 20, 30, 40, 50 ];
if ( x not in list ):
print("x is NOT present in given list")
else: OUTPUT:
print("x is present in given list")
if ( y in list ):
print("y is present in given list")
else:
print("y is NOT present in given list")

Identity Operators:
Identity operators compare the memory locations of two objects. There are two Identity
operators.
• Is Operator
• Not is Operator

‘is’ operator:
It evaluates to true if the variables on either side of the operator point to the same object and
false otherwise.
Example:
x=5
OUTPUT:
if (type(x) is int):
print ("true")
else:
print ("false")

‘isnot’operator –
Evaluates to false if the variables on either side of the operator point to the same object and
true otherwise.
x = 5.2
if (type(x) is not int):
OUTPUT:
print ("true")
else:
print ("false")

Notes Prepared by: Ms. Santhoshini Sahu, Assistant Professor, Dept of CSE, GMRIT
Lecture Notes-7 Python Programming

Expressions:

An expression is a combination of operators and operands. All expressions have a value.


Example: In an expression a + b,
a and b are operands and
+ is an operator.
Following table shows some examples of expressions in Python:

Algebraic Expression Python Expression


abc a*b*c
(m+n)(x+y) (m+n)*(x+y)
ax2+bx+c a*x*x+b*x+c
(p+q)2 (p+q)* (p+q)
(mn)/3 (m*n)/3

Evaluation of an Expression:
The process of determining the expression’s value is called “evaluation of an expression”.
Example:
a = 10
b = 20
print(a+b)
Output: 30
In general, expressions are evaluated using an assignment statement of the form
variable = expression
here expression gets evaluated first and then value is assigned to variable on the left hand
side of an assignment statement.
Example:
a = 10
b = 20
c = a+b
print(c)
Output:
30

Notes Prepared by: Mrs. P. Someswari, Assistant Professor, Dept of CSE, GMRIT
Mixed Type Expressions:
Expressions may contain mixed integer and floating-point elements.
Example:
x=4
y = 10.2
sum = x + y
print(sum)
Here, x is an integer and
y is a floating-point number and
x + y is a floating-point expression, and
the assignment will make the variable sum bind to a floating-point value.
Output:
14.2

Order of evaluations - Precedence and Associativity of Operators:

All Python operators have a precedence and associativity. Python has well-defined rules for
specifying the order in which the operators in an expression are evaluated when the
expression has several operators. For example, multiplication and division have a higher
precedence than addition and subtraction.
Precedence –
Precedence / Priority indicate that which operator has to be evaluated first if the given
expression contains more than one operator.
Example:
The expression
10 - 4 * 2 evaluates to 2.
Here, multiplication is performed before addition, since multiplication has highest precedence
over addition.
Example:
10 - 4 * 2
Output:
2

Notes Prepared by: Mrs. P. Someswari, Assistant Professor, Dept of CSE, GMRIT
Example:
a = 10
b = 22
c=3
x=a*b+c
y=a-b*c
print(x)
223
print(y)
-56
Associativity –
If an expression contains different operators but with same precedence, then associativity
helps to determine the order of operations. For example, multiplication and floor division
have the same precedence. Hence, if both of them are present in an expression, the left one is
evaluated first.
There are 2 types of associativity:
a) Left to right
b) Right to left
Left to right associativity:
Here, the operators are having associativity which is from left to right. For example,
arithmetic operators have left to right associativity.
Example:
The expression 2 - 3 - 4 evaluates to -5.
Here, the evaluation is done from left to right since subtraction operator is left associative.
Example:
# Shows left-right associativity
print(5 * 2 // 3)
Output:
3
Right to left associativity:
Here, the operators are having associativity which is from right to left. For example, the
exponent operator i.e., ** has right-to-left associativity in Python.

Notes Prepared by: Mrs. P. Someswari, Assistant Professor, Dept of CSE, GMRIT
Example:
# Shows the right-left associativity of **
print(2 ** 3 ** 2)
Output:
512, Since 2**(3**2) = 2**9
The assignment operator is a different kind of operator from the arithmetic operators. The
notions of precedence and associativity do not apply in the context of the assignment
operator. Python support a special kind of assignment statement called chained assignment.
Example:
The statement
w=x=y=z
assigns the value of the rightmost variable (i.e., z) to all the other variables (w, x, and y) to its
left.
The following table shows precedence of different operators in Python:

Precedence Name Operator


1 Parenthesis ()[]{}
2 Exponentiation **
Complement, Unary plus
3 ~+–
and minus
4 Multiply, Divide, Modulo / * // %
5 Addition & Subtraction + –
6 Shift Operators >> <<
7 Bitwise AND &
8 Bitwise XOR ^
9 Bitwise OR |
10 Comparison Operators >= <= > <
11 Equality Operators == !=
12 Assignment Operators = += -= /= *=
13 Identity Operators is, is not
14 Membership Operators in, not in
15 Logical Operators and, or, not

Notes Prepared by: Mrs. P. Someswari, Assistant Professor, Dept of CSE, GMRIT
Lecture Notes-8 Python Programming

Conditional Statements:
• Also known as Decision making / Selection statements.
• Decision making is the most important aspect of almost all the programming
languages.
• These statements have the ability to compare values (make decisions) and allows to
run a particular block of code depending on the outcome of the condition i.e., either
TRUE or FALSE.
• Python supports different decision making statements. They are:
a) Simple if,
b) if-else,
c) nested if
d) elif statement
NOTE: Python requires the block to be indented.
Simple if:
Syntax:
The general form/syntax of if statement is
if condition:
statement(s) #if block
Flowchart for if statement is shown in figure:
• Above syntax started with the reserved word if.
• The condition is a Boolean expression that determines
whether or not the body will be executed.
• A colon (:) must follow the condition.
• If the condition is true, then it the block of statement(s) known as “if-block (or) body
of if” gets executed.
• If the condition is false, then control doesn’t enter into if block and executes the
statements followed by if block.
• In Python, the body of if statement is indicated by the indentation.
• The statements within the block must all be indented the same number of spaces from
the left. The body starts with an indentation and the first unintented line marks the
end.

Notes Prepared by: Mrs. P. Someswari, Assistant Professor, Dept of CSE, GMRIT
Example:
num = int(input("enter the number: "))
if num%2 == 0:
print("Number is even")
Output:
enter the number: 10
Number is even
If-Else:
Syntax:
The general form/syntax of if-else statement is
if condition:
statement(s) # if block
else:
statement(s) #else block

Flowchart for if-else statement is shown in


figure:
• If the condition is true, then the if-block is executed. Otherwise, the else-block is
executed.
• The if-else statement provides an else block combined with the if statement which is
executed in the false case of the condition.
• Here, the keywords used are if and else.
Example:
num = int(input("enter the number:"))
if num%2 == 0:
print("Number is even")
else:
print("Number is odd")
Output
enter the number: 11
Number is odd
enter the number: 12
Number is even

Notes Prepared by: Mrs. P. Someswari, Assistant Professor, Dept of CSE, GMRIT
nested if:
When a series of decision are involved, we may have to use more than one if-else statement
in the nested form.
Syntax:
The general form/syntax of nested if is
if condition1:
if condition2:
statement1 # block1
else:
statement2 # block2
else:
if condition3:
statement3 # block3
else:
statement4 # block4
next_statement
Flowchart for nested if is as shown in figure:

Example:
# Example of nested if statement
a=int(input("Enter A: "))
b=int(input("Enter B: "))
c=int(input("Enter C: "))

Notes Prepared by: Mrs. P. Someswari, Assistant Professor, Dept of CSE, GMRIT
if a>b:
if a>c:
g=a
else:
g=c
else:
if b>c:
g=b
else:
g=c
print("Greater = ",g)
Output
Enter A: 10
Enter B: 20
Enter C: 5
Greater = 20

elif statement:
Syntax:
The general form/syntax of elif is
if condition-1:
Statement-1
elif condition-2:
Statement-2
elif condition-3:
Statement-3
............
elif condition-n:
Statement-n
else:
Default Statement

Notes Prepared by: Mrs. P. Someswari, Assistant Professor, Dept of CSE, GMRIT
Flowchart for elif is as shown in figure:

• In Python, elif ladder statement is the same as an else-if statement of other


programming languages.
• Sometimes we need to check multiple conditions and execute the statements
depending on those conditions, this kind of strategy is used.
• In the above syntax, first it checks for condition-1. If it is true, statement-1 will be
executed. If it is false, then it will check condition-2.
• If it is true, statement-2 will be executed. If it is false, then it will check condition-3.
• If it is true, statement-3 will be executed. If it is false, then it will check condition-n..
• If it is true, statement-n will be executed. If it is false, then the default else statement
always execute.
Example:
# Example of elif statement
age = int( input('Enter your age:'))
if age < 5:
ticket_price = 5
elif age < 16:

Notes Prepared by: Mrs. P. Someswari, Assistant Professor, Dept of CSE, GMRIT
ticket_price = 10
else:
ticket_price = 18
print("amount to pay for ticket is",ticket_price,"rupees")
Output:
Enter your age: 4
amount to pay for ticket is 5 rupees
Enter your age: 7
amount to pay for ticket is 10 rupees
Enter your age: 20
amount to pay for ticket is 18 rupees

Notes Prepared by: Mrs. P. Someswari, Assistant Professor, Dept of CSE, GMRIT
Lecture Notes-09 Python Programming

Pass Statement:
The pass statement is a null statement. But the difference between pass and comment is that
comment is ignored by the interpreter whereas pass is not ignored.

The pass statement is generally used as a placeholder i.e. when the user does not know
what code to write. So user simply places pass at that line.

Sometimes, pass is used when the user doesn’t want any code to execute. So user can
simply place pass where empty code is not allowed, like in loops, function definitions,
class definitions, or in if statements. So using pass statement user avoids this error.

Synatax:
Pass

Example 1: Pass Statement can be used in Empty Function:


def PrasadsFunction:
pass
Example 2: Pass Statement can be used in Empty Class
class PrasadsClass:
pass

Example 3: Pass statement can be used in for loop when user doesn’t know what to
code inside the loop
n = 10
for i in range(n):
# pass can be used as placeholder
# when code is to added later
pass

Example 4: Pass statement can be used with conditional statements


a = 10
b = 20
if(a<b):
pass
else:

Notes Prepared by: Mrs. P. Someswari, Assistant Professor, Dept of CSE, GMRIT
print("b<a")

Example 5: Pass statement get executed when the condition is true


li =['a', 'b', 'c', 'd']
for i in li:
if(i =='a'):
pass
else:
print(i)

Iteration Statements:
Iteration repeats the execution of a sequence of code. Iteration is useful for solving many
programming problems. Iteration and conditional execution form the basis for algorithm
construction.
Python supports different iterative/looping statements. They are:
a) while
b) for

while:
Syntax:
The general form/syntax of while is
while expression:
statements #block of statements
Flowchart for while statement is shown in figure:
• The reserved word while begins the while
statement.
• The condition determines whether the body will
be (or will continue to be) executed.
• A colon (:) must follow the condition.
• block is a block of one or more statements to be
executed as long as the condition is true.

Notes Prepared by: Mrs. P. Someswari, Assistant Professor, Dept of CSE, GMRIT
• As a block, all the statements that comprise the block must be indented one level
deeper than the line that begins the while statement.
• The block technically is part of the while statement.
Example:
#printing numbers from 1 to 5 using while
i=1
while i < 6:
print(i)
i = i+1

Output:
1
2
3
4
5
Example:
#factorial of a number in using while
n = int(input("enter a number: "))
f=1
while n>0:
f=f*n
n=n–1
print("factorial is ", f)
Output:
enter a number: 5
factorial is 120
for:
Syntax:
The general form/syntax of for is
for var in sequence:
loop body
for statement flowchart is shown in figure:

Notes Prepared by: Mrs. P. Someswari, Assistant Professor, Dept of CSE, GMRIT
• The for statement iterates over a sequence of
values.
• It can be used to execute a group of statements
repeatedly depending upon the number of
elements in the sequence.
• It can be used to work with sequence like
string, list and tuple.
• Here, the variable takes the value of the item
inside the sequence for each iteration.

• Loop continues until the last item in the sequence is reached.


• The body of for loop is separated from the rest of the code using indentation.
Example:
#Iterating a string using for loop
str = "python"
for i in str:
print(i)
Output:
p
y
t
h
o
n
range( ):
It is a built-in function of Python that generates a sequence of numbers.
The general form of the range expression is
range( begin,end,step )
where
✓ begin is the first value in the range; if omitted, the default value is 0
✓ end is one past the last value in the range; the end value is always required and may
not be omitted

Notes Prepared by: Mrs. P. Someswari, Assistant Professor, Dept of CSE, GMRIT
✓ step is the amount to increment or decrement; if the step parameter is omitted, it
defaults to 1 (countsup by ones).
✓ begin, end, and step must all be integer expressions; floating-point expressions and
other types are not allowed.
Example:
for n in range(21, 0, -3):
print(n, end=' ')
Output:
21 18 15 12 9 6 3

Example:
n = int(input("Enter the number "))
for i in range(1,11):
c = n*i
print(n,"*",i,"=",c)
Output:
Enter the number 5
5*1=5
5 * 2 = 10
5 * 3 = 15
5 * 4 = 20
5 * 5 = 25
5 * 6 = 30
5 * 7 = 35
5 * 8 = 40
5 * 9 = 45
5 * 10 = 50
nested for:
One loop within another loop is known as “nested loop”. Python allows us to nest any
number of for loops inside a for loop.
When a series of decision are involved, we may have to use more than one if-else statement
in the nested form.
Syntax:
Notes Prepared by: Mrs. P. Someswari, Assistant Professor, Dept of CSE, GMRIT
The general form/syntax of nested for is
for var1 in sequence: #outer loop
for var2 in sequence: #inner loop
block of statements
Example:
n = int(input("Enter the number of rows:"))
for i in range(0,n+1):
for j in range(i):
print(i,end = '')
print()

Output:
Enter the number of rows:5
1
22
333
4444
55555
Loop Control Statements:
Loop control statements change execution from its normal sequence. Python supports
different loop control statements. They are:
✓ break
✓ continue
✓ pass

break:
• Break statement in Python is used to bring the control out of the loop and transfers
execution to the statement immediately following the loop.
Syntax:
break
Flowchart for break is as shown in figure:
Example:
#Sample example for break

Notes Prepared by: Mrs. P. Someswari, Assistant Professor, Dept of CSE, GMRIT
count = 0
while count <= 100:
print (count)
count += 1
if count >= 3:
break
Output:
0
1
2

Continue:
• When the continue statement is executed in the loop, the code inside the loop
following the continue statement will be skipped for the current iteration and the next
iteration of the loop will begin.
• Unlike break, continue statement continues the loop.
Syntax:
continue
Flowchart for continue is as shown in figure:
Example:
#Sample example for continue
for x in range(10):
if x % 2 == 0:
continue
print (x)
Output:
1
3
5
7
9
Pass statement:

Notes Prepared by: Mrs. P. Someswari, Assistant Professor, Dept of CSE, GMRIT
• Python has a special statement called pass, which means do nothing.
• We may use the pass statement in our code in places where the language requires a
statement to appear but we wish the program to take no action whatsoever.
• pass statement is a no-operation placeholder that is used when the syntax requires a
statement, but have nothing useful to say.
• It is often used to code an empty body for a compound statement.

Example:
#Sample example for pass
x = int(input(“Enter any value”))
if x < 0:
pass # Do nothing
else:
print(x)
Output:
Enter any value:5
5
Enter any value:-5
Explanation:
• .If entered input is negative, then it executes pass statement and does nothing.
Otherwise, it executes print statement and prints the input.

Notes Prepared by: Mrs. P. Someswari, Assistant Professor, Dept of CSE, GMRIT
Lecture Notes-10 Python Programming

Lists

A list is a sequence of data values called items or elements. An item can be of any type.

➢ The logical structure of a list resembles the structure of a string. Each of the items in a
list is ordered by position.
➢ Like a character in a string, each item in a list has a unique index that specifies its
position.
➢ The index of the first item is 0, and the index of the last item is the length of the list
minus 1.
➢ As sequences, lists and strings share many of the same operators, but they include
different sets of methods.

Here are some real-world examples of lists:

• A shopping list for the grocery store


• A guest list for a wedding
• A recipe, which is a list of instructions
• A text document, which is a list of lines
• The names in a phone

List Literals and Basic Operators:

Literal string values are written as sequences of characters enclosed in quote marks. In
Python, a list literal is written as a sequence of data values separated by commas.

The entire sequence is enclosed in square brackets ([ and ]).

Example list literals:

>>>integers = [1951, 1969, 1984] # A list of integers

>>>fruits = ["apples", "oranges", "cherries"] # A list of strings

>>> empty = [] # An empty list

Notes Prepared by : S Vinodkumar, Assistant Professor, Dept of CSE, GMRIT


>>> colours = [“red”, “green”, “blue”] #A list of colours

A Python list may hold different types of values.


>>> days=['Monday','Tuesday','Wednesday',4,5,6,7.0]

>>> languages=[['English'],['Gujarati'],['Hindi'],'Romanian','Spanish']

List Traversals:

• Python range () method

Example:

# Python3 code to iterate over a list

list = [2, 4, 6, 8, 10]

# getting length of list

length = len(list)

# Iterating the index

# same as 'for i in range(len(list))'

for i in range(length):

print(list[i])

• Python enumerate () method

Example:

# Python3 code to iterate over a list

list = [1, 3, 5, 7, 9]

# Using enumerate()

for i, val in enumerate(list):

print (i, ",",val)

• By using a for Loop

Example:

# Python3 code to iterate over a list

Notes Prepared by : S Vinodkumar, Assistant Professor, Dept of CSE, GMRIT


list = [2, 4, 6, 8, 10]

# Using for loop

for i in list:

print(i)

• By using a while Loop

Example:
# Python3 code to iterate over a list
list = [2, 4, 6, 8, 10]
# Getting length of list
length = len(list)
i=0
# Iterating using while loop
while i < length:
print(list[i])
i += 1

• List Comprehension
• Lambda function
• Python NumPy module
Example 1:

>>> days=['Monday','Tuesday','Wednesday',4,5,6,7.0]
>>> days
Output:

[‘Monday’, ‘Tuesday’, ‘Wednesday’, 4, 5, 6, 7.0]

Example 2:

>>> languages=[['English'],['Gujarati'],['Hindi'],'Romanian','Spanish']

>>> print(languages)
Output:

[[‘English’], [‘Gujarati’], [‘Hindi’], ‘Romanian’, ‘Spanish’]

Indexing

Notes Prepared by : S Vinodkumar, Assistant Professor, Dept of CSE, GMRIT


To access a single element, use its index in square brackets after the list’s name. Indexing
begins at 0.

>>> languages[0]

Output:

[‘English’]

An index cannot be a float value.


>>> languages[1.0]
Output:
Traceback (most recent call last):File “<pyshell#70>”, line 1, in <module>
languages[1.0]
TypeError: list indices must be integers or slices, not float

Slicing:

When you want only a part of a Python list, you can use the slicing operator [].

>>> indices=['zero','one','two','three','four','five']
>>> indices[2:4]
Output
[‘two’, ‘three’]
This returns items from index 2 to index 4-1 (i.e., 3)

>>> indices[:4]
Output
[‘zero’, ‘one’, ‘two’, ‘three’]
This returns items from the beginning of the list to index 3.

>>> indices[4:]
Output
[‘four’, ‘five’]
It returns items from index 4 to the end of the list in Python.

>>> indices[:]
Output
[‘zero’, ‘one’, ‘two’, ‘three’, ‘four’, ‘five’]
This returns the whole list.

Notes Prepared by : S Vinodkumar, Assistant Professor, Dept of CSE, GMRIT


• Negative indices- The indices we mention can be negative as well. A negative index
means traversal from the end of the list.

>>> indices[:-2]
Output
[‘zero’, ‘one’, ‘two’, ‘three’]
This returns item from the list’s beginning to two items from the end.

>>> indices[1:-2]
Output
[‘one’, ‘two’, ‘three’]
It returns items from the item at index 1 to two items from the end.

>>> indices[-2:-1]
Output
[‘four’]
This returns items from two from the end to one from the end.

>>> indices[-1:-2]
Output
[]
This returns an empty Python list, because the start is ahead of the stop for the traversal.

***

Notes Prepared by : S Vinodkumar, Assistant Professor, Dept of CSE, GMRIT


Lecture Notes-11 Python Programming

List Methods:

A method is what you can do to it and change it. To call a method on a construct, you use the
dot-operator(.). Python supports some built-in methods to alter a Python list.

a. append()
It adds an item to the end of the list.

>>> a
Output

[2, 1, 3]

>>> a.append(4)

>>> a
Output

[2, 1, 3, 4]

b. insert()
It inserts an item at a specified position.

>>> a.insert(3,5)

>>> a
Output
[2, 1, 3, 5, 4]
This inserted the element 5 at index 3.

c. remove()
It removes the first instance of an item from the Python list.

>>> a=[2,1,3,5,2,4]

>>> a.remove(2)

>>> a
Output
[1, 3, 5, 2, 4]

Notes Prepared by : S Vinodkumar, Assistant Professor, Dept of CSE, GMRIT


Notice how there were two 2s, but it removed only the first one.

d. pop()
It removes the element at the specified index, and prints it to the screen.

>>> a.pop(3)
Output
2

>>> a
Output
[1, 3, 5, 4]

e. clear()
It empties the Python list.

>>> a.clear()

>>> a
Output
[]
It now has a False value.

>>> bool(a)
Output
False

f. index()
It returns the first matching index of the item specified.

>>> a=[1,3,5,3,4]

>>> a.index(3)
Output
1

g. count()
It returns the count of the item specified.

>>> a.count(3)

Notes Prepared by : S Vinodkumar, Assistant Professor, Dept of CSE, GMRIT


Output
2

h. sort()
It sorts the list in an ascending order.

>>> a.sort()

>>> a
Output
[1, 3, 3, 4, 5]

i. reverse()
It reverses the order of elements in the Python lists.

>>> a.reverse()

>>> a
Output
[5, 4, 3, 3, 1]

List Comprehension:

Creation of a new list just like you would do in mathematics. To do so, type an expression
followed by a for statement, all inside square brackets. You may assign it to a variable. Let’s
make a list for all even numbers from 1 to 20.

>>> even=[2*i for i in range(1,11)]


>>> even
Output
[2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
Optionally, you can add an if-statement to filter out items. If we want to change this list to hold
only those items from 1 to 20 that are even and are divisible by 3, we write the following code.

>>> even=[2*i for i in range(1,11) if i%3==0]


>>> even
Output
[6, 12, 18]

Notes Prepared by : S Vinodkumar, Assistant Professor, Dept of CSE, GMRIT


Lecture Notes-12 Python Programming

Multi-Dimensional List

Multidimensional Lists in Python

A one-dimensional list is a simple list without any sublists. A two-dimensional list is a list that
solely contains many single-dimensional lists. A three-dimensional list solely contains many
two-dimensional lists that solely contains many single-dimensional lists. This concludes that
Multi-dimensional lists are the lists within the lists within the lists within the lists and so on.

Example 1:

>>> grocery_list=[['caramel','P&B','Jelly'],['onions','potatoes'],['flour','oil']]

>>> grocery_list
Output
[[‘caramel’, ‘P&B’, ‘Jelly’], [‘onions’, ‘potatoes’], [‘flour’, ‘oil’]]
This is a grocery Python list with lists in it, where the lists are according to a category.
Or, you can choose to go deeper.
Example 2:

>>> a=[[[1,2],[3,4],5],[6,7]]

>>> a

Notes Prepared by : S Vinodkumar, Assistant Professor, Dept of CSE, GMRIT


Output
[[[1, 2], [3, 4], 5], [6, 7]]
To access the element 4 here, we type the following code into the shell.
Example 3:

>>> a[0][1][1]
Output
4
Example 4:
rows=[]
columns=[]
for i in range(3):
for j in range(3):
columns.append(1)
rows.append(columns)

Output: [[1, 1, 1], [1, 1, 1], [1, 1, 1]]

Example 5:

for i in range(len(rows)):

for j in range(len(columns)):

print(rows[i][j],end="")

print("\n")

Output:

111

111

111

Notes Prepared by : S Vinodkumar, Assistant Professor, Dept of CSE, GMRIT


Lecture Notes-13 Python Programming

Introduction to Strings
A string is a sequence of characters. Strings most often contain nonnumeric characters:

Python recognizes both single quotes (') and double quotes (") as valid ways to delimit a
string value.
The word delimit means to determine the boundaries or limits of something. The left ' symbol
determines the beginning of a string, and the right ' symbol that follows specifies the end of
the string.
If a single quote marks the beginning of a string value, a single quote must delimit the end of
the string.
Similarly, the double quotes, if used instead, must appear in pairs.
You may not mix the two kinds of quotation marks when used to delimit a particular string,
as the following interactive sequence shows:

The interpreter’s output always uses single quotes, but it accepts either single or double
quotes as valid input.

Notes Prepared by: Mr D Siva Krishna, Assistant Professor, Dept of CSE, GMRIT
Consider the following interaction Sequence

Notice that with the missing quotation marks the interpreter does not accept the expression
Fred.

It is important to note that the expressions 4 and '4' are different. One is an integer expression
and the other is a string expression.
All expressions in Python have a type. The type of an expression indicates the kind of
expression it is. An expression’s type is sometimes denoted as its class. At this point we have
considered only integers and strings.
The built in type function reveals the type of any Python expression:

Python associates the type name int with integer expressions and str with string expressions.
The built-in int function creates an actual integer object from a string that looks like an
integer, and the str function creates a string object from the digits that make up an integer:

The expression str(4) evaluates to the string value '4', and int('5') evaluates to the integer
value 5.

Notes Prepared by: Mr D Siva Krishna, Assistant Professor, Dept of CSE, GMRIT
The plus operator (+) works differently for strings; consider:

Programming Exercise:

1. Write a Python Program to print individual characters in a String


S='GMRIT'
for i in S:
print(i, end='')
2. Write a Python program to find the length of the String with and without len()
function
L=len(S)
print(L)
C=0
for i in S:
C=C+1
print("Length of %s is %d", S,C)
3. Write a Python Program to find the reverse of the String with in-built functions
print(S[::-1])
4. Write a Python Program to find the number of words in a String

S="This is GMRIT"

C=len(S.split())

print(C)

Notes Prepared by: Mr D Siva Krishna, Assistant Professor, Dept of CSE, GMRIT
Lecture Notes-14 Python Programming

String Formatting and Multi Line Strings

String Formatting
String formatting is the process of infusing things in the string dynamically and presenting the
string.
There are four different ways to perform string formatting:-
1. Formatting with % Operator.
2. Formatting with format() string method.
3. Formatting with string literals, called f-strings.
4. Formatting with String Template Class

1. Formatting string using % Operator


It is the oldest method of string formatting. Here we use the modulo % operator. The modulo % is
also known as the “string-formatting operator”.
Example: Formatting string using % operator
print("The mangy, scrawny stray dog %s gobbled down" + "the grain-free, organic dog food."
%'hurriedly')
Output: The mangy, scrawny stray dog hurriedly gobbled down the grain-free, organic dog food.

You can also inject multiple strings at a time and can also use variables to insert objects in the
string.
Example: Injecting multiple strings using % operator
x = 'looked'
print("Misha %s and %s around"%('walked',x))
Output:
Misha walked and looked around.
‘%s’ is used to inject strings similarly ‘%d’ for integers, ‘%f’ for floating-point values, ‘%b’ for
binary format. For all formats, conversion methods visit the official documentation.
Example:
print('Joe stood up and %s to the crowd.' %'spoke')
print('There are %d dogs.' %4)
Output:
Joe stood up and spoke to the crowd.

Notes Prepared by: Mr D Siva Krishna, Assistant Professor, Dept of CSE, GMRIT
There are 4 dogs.
Float precision with the placeholder method:
Floating-point numbers use the format %a.bf. Here, a would be the minimum number of digits to be
present in the string; these might be padded with white space if the whole number doesn’t have this
many digits. Close to this, bf represents how many digits are to be displayed after the decimal
point.
Example 1: Float point precision using % operator
print('The value of pi is: %5.4f' %(3.141592))
print('Floating point numbers: %1.0f' %(13.144))
Output:
The value of pi is: 3.1416
Floating point numbers: 13
2. Formatting string using format() method
Format() method was introduced with Python3 for handling complex string formatting more
efficiently. Formatters work by putting in one or more replacement fields and placeholders defined
by a pair of curly braces { } into a string and calling the str.format(). The value we wish to put into
the placeholders and concatenate with the string passed as parameters into the format function.
Syntax: ‘String here {} then also {}’.format(‘something1′,’something2’)
Example: Formatting string using format() method
print('We all are {}.'.format('equal'))
Output:
We all are equal.
The.format() method has many advantages over the placeholder method:
• We can insert object by using index-based position:
Example
print('{2} {1} {0}'.format('directions','the', 'Read'))
Output:

Read the directions.


• We can insert objects by using assigned keywords:
print('a: {a}, b: {b}, c: {c}'.format(a = 1, b = 'Two', c = 12.3))
Output:
a: 1, b: Two, c: 12.3

Notes Prepared by: Mr D Siva Krishna, Assistant Professor, Dept of CSE, GMRIT
• We can reuse the inserted objects to avoid duplication:
print('The first {p} was alright, but the {p} {p} was tough.'.format(p = 'second'))

Output:
The first second was alright, but the second second was tough.
Float precision with the .format() method:
Syntax: {[index]:[width][.precision][type]}
The type can be used with format codes:
• ‘d’ for integers
• ‘f’ for floating-point numbers
• ‘b’ for binary numbers
• ‘o’ for octal numbers
• ‘x’ for octal hexadecimal numbers
• ‘s’ for string
• ‘e’ for floating-point in an exponent format
Example:
print('The value of pi is: %1.5f' %3.141592)
# vs.
print('The value of pi is: {0:1.5f}'.format(3.141592))
Output:
The value of pi is: 3.14159
The value of pi is: 3.14159
3. Formatted String using F-strings
PEP 498 introduced a new string formatting mechanism known as Literal String Interpolation or
more commonly as F-strings (because of the leading f character preceding the string literal). The
idea behind f-strings is to make string interpolation simpler.
To create an f-string, prefix the string with the letter “ f ”. The string itself can be formatted in much
the same way that you would with str.format(). F-strings provide a concise and convenient way to
embed python expressions inside string literals for formatting.
Example: Formatting string with F-Strings
name = 'Ele'
print(f"My name is {name}.")
Output: My name is Ele.

Notes Prepared by: Mr D Siva Krishna, Assistant Professor, Dept of CSE, GMRIT
Example: Lambda Expressions using F-strings

print(f"He said his age is {(lambda x: x*2)(3)}")


Output:
He said his age is 6
Example: Float Precision using F-strings
num = 3.14159
print(f"The value of pi is: {num:{1}.{5}}")
Output:
The value of pi is: 3.1416
4. String Template Class
In the String module, Template Class allows us to create simplified syntax for output specification.
The format uses placeholder names formed by $ with valid Python identifiers (alphanumeric
characters and underscores). Surrounding the placeholder with braces allows it to be followed by
more alphanumeric letters with no intervening spaces. Writing $$ creates a single escaped
Example: Formatting string using Template Class
from string import Template
n1 = 'GMR'
n2 = 'Institute of Technology'
n3 = 'Hello'
n = Template('$n4 ! This is $n5 $n6.')
# pass the parameters into the String Template
print(n.substitute(n4=n3, n5=n1, n6=n2))
Output:
Hello ! This is GMR Institute of technology.
Multiline Strings
Use triple quotes to create a multiline string
It is the simplest method to let a long string split into different lines. You will need to enclose it
with a pair of Triple quotes, one at the start and second in the end.
Example 1: Using triple quotes
my_string = '''The only way to
learn to program is
by writing code.'''

Notes Prepared by: Mr D Siva Krishna, Assistant Professor, Dept of CSE, GMRIT
print(my_string)
Output:
The only way to
learn to program is
by writing code.

Example 2: Using parentheses and a single/double quotes


my_string = ("The only way to \n"
"learn to program is \n"
"by writing code.")
print(my_string)
Output:
The only way to
learn to program is
by writing code.

Example 3: Using \
my_string = "The only way to \n" \
"learn to program is \n" \
"by writing code."
print(my_string)
Output:
The only way to
learn to program is
by writing code.

We can use multiple format conversion types in a single print statement


variable = 12
string = "Variable as integer = %d \n\
Variable as float = %f" %(variable, variable)
print (string)
Output:
Variable as integer = 12
Variable as float = 12.000000

Notes Prepared by: Mr D Siva Krishna, Assistant Professor, Dept of CSE, GMRIT
Lecture Notes-15 Python Programming
String Slicing

Python provides us with a method slice() that creates a ‘slice’ object that contains a set of
‘start’ & ‘stop’ indices and step values. To be specific about the parameters, it is (start, stop,
step).
Slice has two different implementations, i.e. slice have two overload methods, each taking two
different sets of parameters:

• slice(stop) // takes start as 0 & step as 1


• slice (start, stop, step)
o start: is the starting index of the string on which slicing operation has to be
performed. It determines from where slicing of the string will ‘begin’.
o stop: is the stopping index of the slicing, ‘until’ which slicing operation has to
be performed, i.e, stop index is excluded while generating the substring.
o step: It is an optional argument that defines the steps when iterating the list, i.e.
it allows us to skip over elements.

Both slice() implementations return an object of the format slice(start, stop, end).

This returned object can now be used to slice string, list, tuple, set, bytes, or range
objects.

s = "Welcome to GMR Institute of Technology"


s1 = slice(6) # takes start as 0 automatically
print("s1-obj:", s1)
print("s1-res:", s[s1])
s2 = slice(2,8) # using slice(start, end, step) without step
print("s2-obj:", s2)
print("s2-res:", s[s2])
s3 = slice(1, 20, 2) # using slice(start, end, step) with step
print("s3-obj:", s3)
print("s3-res:", s[s3])
Output:
s1-obj: slice(None, 6, None)
s1-res: Welcom

Notes Prepared by: Mr D Siva Krishna, Assistant Professor, Dept of CSE, GMRIT
s2-obj: slice(2, 8, None)
s2-res: lcome
s3-obj: slice(1, 20, 2)
s3-res: ecm oGRIsi
Explanation:
Slice() has two implementations, one with a single parameter and another with three
parameters. Implementation with one parameter takes ‘stop’ index as the only and mandatory
parameter whereas Implementation with three parameters takes ‘start’ index, ‘stop’ index, and
OPTIONAL ‘step’ value as well.
In the above example ( check s1, s2 & s3 in the code snippet & output):
• In s1: We first used slice() that takes only one ‘stop’ parameter. In the output, we
received substring as “Welcom” as the ‘start’ index was automatically set to ‘0’ and
‘stop’ was set as 6.
• In s2: After that, we used slice() with a three parameter-method but chose not to
provide an optional ‘step’ parameter. In the output, we received a substring from index
‘2’ until ‘7’, as we provided ‘start’ as ‘2’ & ‘stop’ as ‘8’.
• In s3: We implement slice() with ‘step’ as well. As we provided ‘step’ as 2. In the
output, we received a substring by advancing to every 2nd element starting from index
1 to 20
Hence, now it’s clear that ‘step’ value determines with what value will your iterator (while
forming the substring) advance or increment.

Indexing Syntax
Indexing syntax of a slice is a shorthand or a better substitute of slice() as it’s easier to
understand and execute. It’s one of those operations and syntax that you appreciate as a
developer and subconsciously lookout to apply in your code as it really is a cool operation!
Indexing Syntax:
String [start : stop : step]
So here, instead of creating a slice object first and then implementing it on the string, we
directly use the indexing syntax that performs the same operation.
Example:
s = "Welcome to GMR Institute of Technology"
print("s1", s[:6])
print("s2", s[2 : 7]) # using indexing syntax for slice(start, end, step) without step

Notes Prepared by: Mr D Siva Krishna, Assistant Professor, Dept of CSE, GMRIT
print("s3", s[1 : 20 : 2]) # using indexing syntax for slice(start, end, step)
Output:
s1 Welcom
s2 lcome
s3 ecm oGRIsi

Note:
• ‘Step’ can never be zero.
• String[ : : ] => start = 0, stop = length of string, step = 1.
• String[2 : : ] => start = 2, stop = length of string, step = 1
• String[ :2: ] => start = 0, stop = 2, step = 1
• String[:6] OR String[1:6] => are valid syntaxes as ‘step’ is an optional parameter for
this operation.

Using Negative index


‘Start’ and ‘stop’ indices and the step can have a negative value, respectively.
Program:
s = "Welcome to GMR Institute of Technology"
# -x means xth element from the end.
print("indexing syntax without step:", s[-16 : -4])
# using step to fetch every 2nd character from start index until end index
print("indexing syntax with step:", s[-16 : -4 : 2])
# replicating above code using slice object
sliceObj = slice(-16, -4)
print("slice object without step:", s[sliceObj])
sliceObj = slice(-16, -4, 2)
print("slice object with step:", s[sliceObj])
Output:
indexing syntax without step: te of Techno
indexing syntax with step: t fTcn
slice object without step: te of Techno
slice object with step: t fTcn

Reversing a substring using negative step

s = "Welcome to GMR Institute of Technology"

Notes Prepared by: Mr D Siva Krishna, Assistant Professor, Dept of CSE, GMRIT
# reversing complete string
s1 = s[::-1]
print("s1:", s1)
# reversing complete string by stepping to every 2nd element
s2 = s[::-2]
print("s2:", s2)
# reversing from 10th index until start, 'stop' index here automatically will be till starting of the
string
s3 = s[10::-1]
print("s3:", s3)
# reversing from end until 10th index, 'start' index will automatically be the first element
s4 = s[:10:-1]
print("s4:", s4)
# reversing from 16th index till 10th index
s5 = s[16:10:-1]
print("s5:", s5)
# this will return empty, as we're not reversing here. But NOTE that this 'start' cannot be
greater than ‘stop’ until & unless we're reversing
s6 = s[11:2]
print("s6:", s6)
# reversing from 14th index from the end until 4th index from the end.
s7 = s[-4:-14:-1]
print("s7:", s7)
Output:
s1: ygolonhceT fo etutitsnI RMG ot emocleW
s2: yoohe oeuisIRGo mce
s3: ot emocleW
s4: ygolonhceT fo etutitsnI RMG
s5: nI RMG
s6:
s7: lonhceT fo

Notes Prepared by: Mr D Siva Krishna, Assistant Professor, Dept of CSE, GMRIT
Lecture Notes-16 Python Programming

Introduction to Tuple, Dictionary and Sets:


Dictionary and dictionary Operations
INTRODUCTION TO TUPLE
Tuple is exactly same as list except that it is immutable. i.e, once we create a Tuple object, we
cannot perform any changes in the object. Hence tuples are Read Only version of List. We
cannot perform operations like append (), extend (), insert (), remove (), pop () and clear () on
tuples.
Creating tuples:
We can create a tuple by writing elements separated by commas inside parenthesis (). The
elements can be of same or different data types.
Syntax: tuple_name = (“element1”, “element2”, “element3”)
1. Empty tuple
tuple1 = () #empty tuple
2. Tuple with one element: creation of single valued tuple, parenthesis are optional,
should end with comma.
tuple2 = (10,)
3. Tuple with different type of elements i.e, heterogeneous objects are allowed.
tuple3 = (10, 20, -30, -40.5, ‘Vijayawada’, ‘NEWDELHI’)
4. Tuple with only one type of elements
tuple4 = (10, 20, 30) #tuple with integers
5. Tuple with no braces
tuple5 = 1, 2, 3, 4

Notes Prepared by: Mrs A Vineela, Assistant Professor, Dept of CSE, GMRIT
Program converting list to tuple: we can convert a list to tuple using tuple() function?
Program: tup.py
list = [1, 2, 3]
tpl = tuple(list)
print(tpl)
output: python tup.py

INTRODUCTION TO DICTIONARIES:
A Dictionary represents a group of elements arranged in the form of key-value pairs. In
dictionary, the first element is considered as ‘key’ and immediate next element is taken as its
‘value’. The key and its value are separated by colon (: ).
All the key-value pairs in a dictionary are inserted in curly braces {}.

It is the mutable data-structure. The dictionary is defined into element Keys and values.

• Keys must be a single element


• Value can be any type such as list, tuple, integer, etc.

Syntax: d = { <key> : <value>,

<key> : <value>,

<key> : <value>

Example: dict = {‘name’ : ’tom’, ’age’ : ’10’}

In the above dictionary dict, the keys name and age are the string that is an immutable object.

Notes Prepared by: Mrs A Vineela, Assistant Professor, Dept of CSE, GMRIT
Example:

Python provides the built-in function dict() method which is also used to create dictionary. The
empty curly braces {} is used to create empty dictionary.

Accessing the Dictionary values: To access the elements of a dictionary we should not use
indexing or slicing. The values in dictionary can be accessed by using keys and keys are unique
in the dictionary.

For example: dict[0] or dict[1:3] etc, expressions will give error.

Notes Prepared by: Mrs A Vineela, Assistant Professor, Dept of CSE, GMRIT
To access the value associated with the key, we need to mention key name inside the square
braces.

Example:

Changing and Adding Dictionary elements: dictionaries are mutable we can change or add
new items using an assignment operator.
If the key is already present, then the existing value will be updated. In case the key is not
7present, a new (key: value) pair is added to the dictionary.
Example:

Removing elements from dictionary:


The items of the dictionary can be deleted using del keyword.

Notes Prepared by: Mrs A Vineela, Assistant Professor, Dept of CSE, GMRIT
Example:

Notes Prepared by: Mrs A Vineela, Assistant Professor, Dept of CSE, GMRIT
Lecture Notes-17 Python Programming
Dictionary Methods
Dictionary Methods: Various methods are provided to process the elements of a dictionary.
These methods generally retrieve or manipulate the contents of a dictionary.

Method Description

clear() Removes all items from the dictionary.

copy() Returns a shallow copy of the dictionary.

fromkeys(seq[, Returns a new dictionary with keys from seq and value
v]) equal to v (defaults to None).

Returns the value of the key. If the key does not exist,
get(key[,d])
returns d (defaults to None).

Return a new object of the dictionary's items in (key, value)


items()
format.

keys() Returns a new object of the dictionary's keys.

Removes the item with the key and returns its value or ‘d’
pop(key[,d]) if key is not found. If d is not provided and the key is not
found, it raises KeyError.

Removes and returns an arbitrary item (key, value). Raises


popitem()
KeyError if the dictionary is empty.

Returns the corresponding value if the key is in the


setdefault(key[,d]) dictionary. If not, inserts the key with a value of d and
returns d (defaults to None).

Updates the dictionary with the key/value pairs from other,


update([other])
overwriting existing keys.

values() Returns a new object of the dictionary's values

Notes Prepared by : Mrs A Vineela, Assistant Professor, Dept of CSE, GMRIT


1. clear(): the clear() method removes all the elements from a dictionary.
Syntax: dictionary.clear()
Example:

2. copy(): A copy() method returns a copy of the specified dictionary.


Syntax: dictionary.copy()
Example:

3. formkeys(): The formkeys() methods returns a dictionary a specified keys and


specified values.
Syntax: dict.formkeys(keys,value)
Example:

4. get(): The get method return the value of the item with the specific key.
Syntax: dictionary.get(keyname,value)
Example:

Notes Prepared by : Mrs A Vineela, Assistant Professor, Dept of CSE, GMRIT


5. items(): the items() method returns a view object. The view object contains the key-
value pair of dictionary, as tuples in a list.
Syntax: dictionary.items()
Example:

6. keys(): the keys() method returns a view object. The view object contains the keys of
the dictionary, as a list. The view object will reflect any changes done to the
dictionary.
Syntax: dictionary.keys()
Example:

7. pop(): The pop() method removes the specific items from the dictionary. The value
of the removed item is the return value of the pop() method.
Syntax: dictionary.pop(keyname, defaultvalue)
Example:

Notes Prepared by : Mrs A Vineela, Assistant Professor, Dept of CSE, GMRIT


8. popitem(): The popitem() method removes the item that was last inserted into the
dictionary. In versions before 3.7, the popitem() method removes a random item. The
removed item return value of the popitem() method as tuple.
Syntax: dictionary.popitem()
Example:

9. setdefault(): The setdefault() method returns the value of the item with the specific
key. If the key does not exist, insert the key, with the specific value.
Syntax: dictionary.setdefault(keyname, value)
Example:

10. update(): The update() method inserts the specified items to the dictionary. The
specified item can be a dictionary, or an iterable object with the key value pairs.
Syntax: dictionary.update(iterable)
Example:

Notes Prepared by : Mrs A Vineela, Assistant Professor, Dept of CSE, GMRIT


11. values(): The values() method returns a view object. The view object contains the
values of the dictionary, as a list. The view object will reflect any changes done to the
dictionary.
Syntax: dictionary.values()
Example:

1. Write a python Program to Create Dictionary of Numbers 1 to n in (x, x*x)


form?

Program: num.py

n=int(input("Input a number "))


dict = {}
for x in range(1,n+1):
dict[x]=x*x
print(dict)

output: python num.py

Input a number 15
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81, 10: 100, 11: 121, 12: 144, 13: 169, 14:
196, 15: 225}

Notes Prepared by : Mrs A Vineela, Assistant Professor, Dept of CSE, GMRIT


2. Write a program to accept student name and marks from the keyboard and
creates a dictionary. Also display student marks by taking student name as
input?
Program: student.py
n=int(input("Enterthe number of students: "))
d = {}
for i in range(n):
name=input('enter student name:')
marks=int(input("Enter Student Marks: "))
d[name]=marks
while True:
name=input("Enter Student Name to get Marks: ")
marks=d.get(name,-1)
if marks== -1:
print("Student Not Found")
else:
print("The Marks of",name,"are",marks)
option=input("Do you want to find another student marks[Yes|No]")
if option=="no":
break
print("Thanksfor using our application")

output: python student.py


Enter the number of students: 3
enter student name:a
Enter Student Marks: 34
enter student name:b
Enter Student Marks: 45
enter student name:c
Enter Student Marks: 45
Enter Student Name to get Marks: c
The Marks of c are 45
Do you want to find another student marks[Yes|No]no
Thanksfor using our application

Notes Prepared by : Mrs A Vineela, Assistant Professor, Dept of CSE, GMRIT


Notes Prepared by : Mrs A Vineela, Assistant Professor, Dept of CSE, GMRIT
Lecture Notes-18 Python Programming
Sets and Set Operations
Sets: set is an unordered collection data type with no duplicate elements. Sets are iterable and
mutable. The elements appear in an arbitrary order when sets are iterated.
Set objects are mutable i.e once we create set object we can perform any changes in that
object based on our requirement.
The major advantage of using a set, as opposed to a list, is that it has a highly optimized
method for checking whether a specific element is contained in the set.
Creating a set:
A set is created by using set() function or placing all the elements within the curly braces
with comma separation
Example 1:
s = {1,2,3,4,5}
print(type(s))
print(s)
output:
<class 'set'>
{1, 2, 3, 4, 5

Example 2:
#using set() function
i={1,2,3,4,5}
s=set(i)
print(s)
k=set(range(6))
print(k)
output:
{1,2 3 4,5}
{0,1,2,3,4,5}
Example 3: creating set by using list
#using list
#there are some duplicates in it
s=set(['c','c++','java','c',1,2,5,2,7,5,1,2])

Notes Prepared by : Mrs A Vineela, Assistant Professor, Dept of CSE, GMRIT


print(s)
output:
{ 1, 2, ‘c’, 5, 7, ‘c++’, ‘java’}
Adding element to a set:
Using add() method: Elements can be added to the Set by using built-in add() function. Only
one element at a time can be added to the set by using add() method, loops are used to add
multiple elements at a time with the use of add() method .
Note – Lists cannot be added to a set as elements because Lists are not hashable whereas
Tuples can be added because tuples are immutable and hence Hashable.
Example 1:
# Creating a Set
set1 = set()
print("Initial blank Set: ")
print(set1)
# Adding element and tuple to the Set
set1.add(8)
set1.add(9)
set1.add((6,7))
print("\nSet after Addition of Three elements: ")
print(set1)
# Adding elements to the Set
# using Iterator
for i in range(1, 6):
set1.add(i)
print("\nSet after Addition of elements from 1-5: ")
print(set1)
output:
Initial blank Set:
set()

Set after Addition of Three elements:


{8, 9, (6, 7)}

Set after Addition of elements from 1-5:

Notes Prepared by : Mrs A Vineela, Assistant Professor, Dept of CSE, GMRIT


{1, 2, 3, 4, 5, 8, 9, (6, 7)}

Using update() method


For addition of two or more elements update() method is used. The update() method accepts
lists, strings, tuples as well as other sets as its arguments. In all of these cases, duplicate
elements are avoided.
Example 2:
# Addition of elements to the Set
# using Update function
set1 = set([ 4, 5, (6, 7)])
set1.update([10, 11])
print("\nSet after Addition of elements using Update: ")
print(set1)
output:
Set after Addition of elements using Update:
{10, 11, 4, 5, (6, 7)}
Accessing values in a set:
Set items cannot be accessed by referring to an index, since sets are unordered the items has
no index. But you can loop through the set items using a for loop, or ask if a specified value
is present in a set, by using the in keyword.
Example 1:
# Creating a set
set1 = set(["Hi", "hello", "morning"])
print("\nInitial set")
print(set1)
# Accessing element using
# for loop
print("\nElements of set: ")
for i in set1:
print(i, end=" ")
# Checking the element
# using in keyword
print("morning" in set1)

Notes Prepared by : Mrs A Vineela, Assistant Professor, Dept of CSE, GMRIT


output:
Initial set
{'morning', 'hello', 'Hi'}

Elements of set:
morning hello Hi True

Removing elements from set:


Elements can be removed from the Set by using built-in remove() function but a KeyError a
rises if element doesn’t exist in the set. To remove elements from a set without KeyError, us
e discard(), if the element doesn’t exist in the set, it remains unchanged.

Example 1:
# Deletion of elements in a Set
# Creating a Set
set1 = set([1, 2, 3, 4, 5, 6,
7, 8, 9, 10, 11, 12])
print("Initial Set: ")
print(set1)

# Removing elements from Set


# using Remove() method
set1.remove(5)
set1.remove(6)
print("\nSet after Removal of two elements: ")
print(set1)

# Removing elements from Set


# using Discard() method
set1.discard(8)
set1.discard(9)
set1.discard(5) #already removed but doesnot sow any error
print("\nSet after Discarding two elements: ")
print(set1)

# Removing elements from Set


# using iterator method
for i in range(1, 5):
set1.remove(i)
print("\nSet after Removing a range of elements: ")
print(set1)

output:
Initial Set:
{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}

Notes Prepared by : Mrs A Vineela, Assistant Professor, Dept of CSE, GMRIT


Set after Removal of two elements:
{1, 2, 3, 4, 7, 8, 9, 10, 11, 12}

Set after Discarding two elements:


{1, 2, 3, 4, 7, 10, 11, 12}

Set after Removing a range of elements:


{7, 10, 11, 12}

Set Operations:
Sets can be used to carry out mathematical set operations like union, intersection, difference
and symmetric difference. We can do this with operators or methods.
1. Set Union
2. Set Intersection
3. Set Difference
4. Set Symmetric Difference

1. Set Union: Union of A and B is a set of all elements from both sets. Union is performed
using ‘|’ operator. Same can be accomplished using the union() method.

2. Set Intersection: intersection of A and B is a set of elements that are common in both
the sets. Intersection is performed using ‘&’ operator. Some can be accomplished using
the intersection() method.

Notes Prepared by : Mrs A Vineela, Assistant Professor, Dept of CSE, GMRIT


3. Set Difference: Differnce of set B from set A (A-B) is a set of elements what are only
in A but not in B. similarly, B-A is a set of elements in B but not in A.Difference is
performing using ‘-‘ operator. Same can be accomplished using the difference()
method.

4. Set Symmetric Difference: symmetric difference of A and B is a set of elements in A


and B but not in both (excluding the intersection). Symmetric difference is performed
using ‘^’ operator. Same can be accomplished using the method
symmetric_difference().

Notes Prepared by : Mrs A Vineela, Assistant Professor, Dept of CSE, GMRIT


Write a program to print different vowels present in a given word?
Program: vow.py
w=input("enter words to search for vowels")
s=set(w)
v={'a','e','i','o','u'}
d=s.intersection(v)
print('the different vowels in word {} are {}'.format(w,d))

output: python vow.py

Notes Prepared by : Mrs A Vineela, Assistant Professor, Dept of CSE, GMRIT


Lecture Notes-19 Python Programming

Tuple- Tuple Operations and Methods

Tuple:
• Tuple is exactly same as list except that it is immutable. i.e once tuple object is created,
then any specific changes in that object couldn’t be done. Hence Tuple is read only
version of List.
• If our data is static, then Tuple is used.
• Heterogeneous objects are allowed.
• We can preserve insertion order and we can differentiate duplicate objects by using
index. Hence index will play very important role in tuple also.
• Tuple support both +ve and -ve index. +ve index means forward direction (from left to
right) and -ve index means backward direction (from right to left).
• We can represent Tuple elements within Parenthesis and with comma separator
Example:
t=10,20,30,40
print(t)
print(type(t))
Output:
(10,20,30,40)
<class ‘tuple’>
Tuple creation:
t=()
Creation of empty tuple
t=(10,)
t=10, creation of single valued tuple ,parenthesis are optional, should ends with comma
t=10,20,30
t=(10,20,30) creation of multi values tuples & parenthesis are optional
By using tuple() function:
list=[10,20,30]
t=tuple(list)
print(t)

Notes Prepared by : L.Swathi, Assistant Professor, Dept of IT, GMRIT


t=tuple(range(10,20,2))
print(t)

Accessing elements of tuple:


We can access either by index or by slice operator
By using index:
t=(10,20,30,40,50,60)
print(t[0]) #10
print(t[-1]) #60
print(t[100]) Index Error: tuple index out of range
By using slice operator:
t=(10,20,30,40,50,60)
print(t[2:5])
print(t[2:100])
print(t[::2])
Output:
(30, 40, 50)
(30, 40, 50, 60)
(10, 30, 50)
Tuple Operations:
(+):
The + operator returns a tuple containing all the elements of the first and the second tuple
object.
>>>t1=(10,20,30)
>>>t2=(40,50,60)
>>>t3=t1+t2
>>>print(t3) # (10,20,30,40,50,60)
(*):
The * operator Concatenates multiple copies of the same tuple.
. >>>t1=(10,20,30)
>>>t2=t1*3
>>>print(t2) # (10,20,30,10,20,30,10,20,30)
Notes Prepared by : L.Swathi, Assistant Professor, Dept of IT, GMRIT
([]):
The [] operator returns the item at the given index. A negative index counts the position from
the right side.
>>>t1=(1,2,3,4,5,6)
>>>t1[3]
4
>>>t1[-2]
5
([:]):

The [:] operator returns the items in the range specified by two index operands separated by
the: symbol.
If the first operand is omitted, the range starts from zero. If the second operand is omitted, the
range goes up to the end of the tuple.

>>>t1=(1,2,3,4,5,6)
>>>t1[1:3]
(2, 3)
>>>t1[3:]
(4, 5, 6)
>>>t1[:3]
(1, 2, 3)
in:

The in operator returns true if an item exists in the given tuple.


>>> t1=(1,2,3,4,5,6)
>>> 5 in t1
True
>>> 10 in t1
False
not in:

The not in operator returns true if an item does not exist in the given tuple.
>>> t1=(1,2,3,4,5,6)
>>> 4 not in t1
False
>>> 10 not in t1
True

Functions of Tuple:

1. len()

Notes Prepared by : L.Swathi, Assistant Professor, Dept of IT, GMRIT


To return number of elements present in the tuple
Eg: t=(10,20,30,40)
print(len(t)) #4
2. count()

To return number of occurrences of given element in the tuple


Eg: t=(10,20,10,10,20)
print(t.count(10)) #3

3. index()

Returns index of first occurrence of the given element. If the specified element is not
available then we will get Value Error.
Eg: t=(10,20,10,10,20)
print(t.index(10)) #0
print(t.index(30)) Value Error: tuple .index(x): x not in tuple

4. sorted()
To sort elements based on default natural sorting order
t=(40,10,30,20)
t1=sorted(t)
print(t1)
print(t)
Output:
[10, 20, 30, 40]
(40, 10, 30, 20)

5. min() and max() functions:


These functions return min and max values according to default natural sorting order.
t=(40,10,30,20)
print(min(t)) #10
print(max(t)) #40

6. cmp():
Notes Prepared by : L.Swathi, Assistant Professor, Dept of IT, GMRIT
It compares the elements of both tuples. If both tuples are equal then returns 0 If the first
tuple is less than second tuple then it returns -1 If the first tuple is greater than second
tuple then it returns +1
t1=(10,20,30)
t2=(40,50,60)
t3=(10,20,30)
print(cmp(t1,t2)) # -1
print(cmp(t1,t3)) # 0 6.
print(cmp(t2,t3)) # +1
Note: cmp() function is available only in Python2 but not in Python 3.

Tuple Packing and Unpacking:


We can create a tuple by packing a group of variables.
a=10
b=20
c=30
d=40
t=a,b,c,d
print(t) #(10, 20, 30, 40)
Here a,b,c,d are packed into a tuple t. This is nothing but tuple packing.

Tuple unpacking is the reverse process of tuple packing. We can unpack a tuple and assign its
values to different variables
t=(10,20,30,40)
a,b,c,d=t
print("a=",a,"b=",b,"c=",c,"d=",d)

Output: a= 10 b= 20 c= 30 d= 40

***

Notes Prepared by : L.Swathi, Assistant Professor, Dept of IT, GMRIT


Lecture Notes-20 Python Programming

Methods available in Python- eval Method and Its Use Cases

eval is a built-in- function used in python, eval function parses the expression argument and
evaluates it as a python expression. In simple words, the eval function evaluates the “String” like
a python expression and returns the result as an integer.

Syntax eval(expression, [globals[, locals]])

Arguments or Parameters
The arguments or parameters of eval function are strings, also optionally global and locals can be
used as an argument inside eval function, but the globals must be represented as a dictionary and
the locals as a mapped object.

Return Value
The return value would be the result of the evaluated expression. Often the return type would be
an integer.

Use of Eval Function


Eval function is mostly used in situations or applications which need to evaluate mathematical
expressions. Also if the user wants to evaluate the string into code then can use eval function,
because eval function evaluates the string expression and returns the integer as a result.

Use Case-1:

Compare eval() and Input():

input = input("Enter any number of your choice:")


print(input)
print(type(input))
--------------------------------------------------------------------
Enter any number of your choice: 10 + 10
10 + 10
<class 'str'>

An integer is entered as 10+ 10 where expecting a result of 20 (10 + 10) but the input method
returned a string of the same input entered.

Use Case-2:

Notes Prepared by: L.SWATHI, Assistant Professor, Dept of IT, GMRIT


eval = eval(input("Enter any number of your choice"))
print(eval)
print(type(eval))
--------------------------------------------------------------------
Enter any number of your choice: 10 + 10
20
<class 'int'>

In the case of eval, it returned the evaluated expression 20 in the form of an integer given the
string as input. 10 + 10 is an expression that returns 20 as a result.

Use Case-3:

Mathematical operations using eval function

evaluate = input(“Enter what operation x has to perform: “)


print(evaluate)
print(type(evaluate))
--------------------------------------------------------------------
Enter what operation x has to perform: x + x + 100 - 35 + 5 * 80
x + x + 100 - 35 + 5 * 80
<class 'str'>

x = 10
print(type(x))
--------------------------------------------------------------------
<class 'int'>

expression = eval(evaluate)
print(expression)
print(type(expression))
--------------------------------------------------------------------
485
<class 'int'>

Notes Prepared by: L.SWATHI, Assistant Professor, Dept of IT, GMRIT


More Methods-

1.abs(x)- The abs() method returns the absolute value of the given number and returns a
magnitude of a complex number.
Syntax: abs (num)

Parameters: An int, float, or complex number.


print("Absolute value of -10 is: ",abs(-10)) #10
print("Absolute value of -0b10011 is: ", abs(-0b10011)) #19

2.all(iterable)- The all() method checks whether all the elements in an iterable are truthy values
or not. It returns true if all elements in the given iterable are nonzero or True. Else, it returns
False.
Syntax: all (iterable)

Parameters: A list, tuple, string, set, or dictionary object.


nums = [1, 2, 3, -4, -5]
print(all(nums)) # Returns True
data = [1, 'Phone', 12.5, 5, False]
print(all(data)) # Returns False because of False

3.any(iterable)- The any() method returns True if at least one element in the given iterable is the
truthy value or boolean True. It returns False for empty or falsy value (such as 0, False, none).
Syntax: any(iterable)

Parameters: An iterable (list, tuple, string, set, dictionary).


nums = [0, 1, 2, 3, 4, 5]
print(any(nums)) # returns True

4.ascii()- This method in Python returns a string containing a printable representation of an


object for non-alphabets or invisible characters such as tab, carriage return, form feed, etc. It
escapes the non-ASCII characters in the string using \x, \u or \U escapes.
Syntax: ascii(object)

Parameters: Any type of object.

5.bin(x)- The bin() method converts an integer number to a binary string prefixed with 0b.
Syntax: bin(num)
Parameters: An integer.

Notes Prepared by: L.SWATHI, Assistant Professor, Dept of IT, GMRIT


print("Binary equivalent of 5 is: ", bin(5)) # 0b101

6.bytearray()- The bytearray() method returns a bytearray object, which is an array of the given
bytes. The bytearray class is a mutable sequence of integers in the range of 0 to 256.
Syntax: bytearray(source, encoding, errors)

Parameters: An integer or iterable to convert it to a byte array.


If the source is a string, it must be with the encoding parameter.
If the source is an integer, the array will have that size and will be initialized with null bytes.
If the source is the iterable object, it must have integer elements only in the range 0 to 256.
encoding: The encoding of the string if the source is a string.
errors: The action to take if the encoding conversion fails.

7.Chr()-The chr() method returns the string representing a character whose Unicode code
point is the integer.
Syntax: chr(integer)

Parameters: An integer from 0 through 1,114,111 (0x10FFFF in base 16).


print("The character value of 65 is: ", chr(65)) #A
print("The character value of 90 is: ", chr(90)) #Z

8.len()-This function returns the length of the object. It returns total elements in an iterable or
the number of chars in a string.
Syntax: len(object)
print("Total Elements in list: ", len([1,2,3,4,5])) # 5
print("Total Elements in tuple: ",len((1,2,3,4,5))) #5

9.max()-This method returns the largest value from the specified iterable or multiple
arguments.
Syntax: max(iterable, key, default)

Parameters: 1.iterable: An iterable (list, tuple, set, dict, string).


2. key: The built-in or user-defined function to be used for comparison.
3. default: The value to be returned if the iterable is empty.
Example: nums = [1, 7, 8, 5, 4, 6, 2, 3]
largest = max(nums)
print("The largest number is: ", largest)

Output: The largest number is: 8

Notes Prepared by: L.SWATHI, Assistant Professor, Dept of IT, GMRIT


10.range()-This constructor method returns an object of the range class, which is an immutable
sequence type. The range() method returns the immutable sequence numbers between the
specified start and the stop parameter, increment by step parameter.
Syntax: range(start, stop, step)
Example: num_range = range(5) #start=0, stop=5, step=1
print(type(num_range))
print(num_range)
print('Values = ', num_range[0], num_range[1], num_range[2], num_range[3], num_range[4])

Output: <class 'range'>


range(0, 5)
Values = 0 1 2 3 4

11.repr()-This method returns a string containing a printable representation of an object. This


function calls the underlying __repr__() function of the object.
Syntax: repr(obj)
Example:

print(repr(10)) #'10'
print(repr(10.5)) #'10.5'

12.round()-The round() method returns a floating-point number, rounded to the specified


number of the decimal point.
Syntax: round(number, digits)

Example:

print(round(1)) #1
print(round(1.4)) #1
print(round(1.5)) #2
print(round(1.6)) #2
13.split()-The split() function breaks a string based on set criteria. You can use it to split a string
value from a web form. Or you can even use it to count the number of words in a piece of text.

words="column1 column2 column3"


words=words.split(" ")
print(words)
Output: ['column1', 'column2', 'column3']

Notes Prepared by: L.SWATHI, Assistant Professor, Dept of IT, GMRIT


14.getattr()-Python's getattr() returns the attribute of an object. It accepts two parameters: the
class and the target attribute name.

Example:

class ty:
def __init__(self, number, name):
self.number = number
self.name = name
a = ty(5*8, "Idowu")
b = getattr(a, 'name')
print(b)
Output: Idowu

15.strip()- Python's strip() removes leading characters from a string. It repeatedly removes the
first character from the string, if it matches any of the supplied characters.
Example:

st = " Python tutorial"


st = st.strip(" P")
print(st)
Output: ython tutorial

Students can explore More Methods based upon the Need in their Program.

***

Notes Prepared by: L.SWATHI, Assistant Professor, Dept of IT, GMRIT


Lecture Notes-21 Python Programming

Filter
filter()
The filter() function extracts elements from an iterable (list, tuple etc.) for which a function
returns True.
Syntax:
filter(function, iterable)

Arguments:
The filter() function takes two arguments:
function - a function to be run for each item in the iterable
iterable - an iterable like sets, lists, tuples etc.

Return Value:
The filter() function returns an iterator.
Note: You can easily convert iterators to sequences like lists, tuples, strings etc.

Example 1:
This simple example returns values higher than 5 using filter function.
def filterdata(x):
if x>5:
return x
result = filter(filterdata,(1,2,6))
print(list(result))
Output: [6]

Example 2:
letters = ['a', 'b', 'd', 'e', 'i', 'j', 'o']
# a function that returns True if letter is vowel
def filter_vowels(letter):
vowels = ['a', 'e', 'i', 'o', 'u']
return True if letter in vowels else False

Notes Prepared by: L.SWATHI, Assistant Professor, Dept of IT, GMRIT


filtered_vowels = filter(filter_vowels, letters)
vowels = tuple(filtered_vowels)
print(vowels)
Output: ('a', 'e', 'i', 'o')

Here, the filter() function extracts only the vowel letters from the letters list. Each element of
the letters list is passed to the filter_vowels() function. If filter_vowels() returns True, that
element is extracted otherwise it's filtered out.

Using Lambda Function Inside filter()


numbers = [1, 2, 3, 4, 5, 6, 7]
# the lambda function returns True for even numbers
even_numbers_iterator = filter(lambda x: (x%2 == 0), numbers)
# converting to list
even_numbers = list(even_numbers_iterator)
print(even_numbers)

Output: [2,4,6]

Here, we have directly passed a lambda function inside filter(). lambda function returns True for
even numbers. Hence, the filter() function returns an iterator containing even numbers only.

Using None as a Function Inside filter()


random_list = [1, 'a', 0, False, True, '0']
filtered_iterator = filter(None, random_list)
filtered_list = list(filtered_iterator)
print(filtered_list)

Output: [1, 'a', True, '0']


When None is used as the first argument to the filter() function, all elements that are truly
values (gives True if converted to boolean) are extracted.

Notes Prepared by: L.SWATHI, Assistant Professor, Dept of IT, GMRIT


Lecture Notes-22 Python Programming

Reduce
Map, Filter, and Reduce are paradigms of functional programming. They allow the programmer to
write simpler, shorter code, without necessarily needing to bother about intricacies like loops and
branching.

Essentially, these three functions allows to apply a function across a number of iterables, in one fell
swoop. Map and filter come built-in with Python and require no importing. Reduce, however, needs
to be imported as it resides in the functools module.

Reduce():

reduce() isn't a built-in function anymore, and it can be found in the functools module. The reduce()
function applies a provided function to ‘iterables’ and returns a single value, as the name implies.

reduce() works differently than map() and filter().It does not return a new list based on
the function and iterable we've passed. Instead, it returns a single value.

The syntax is:


reduce(func, iterable[, initial])

Where func is the function on which each element in the iterable gets cumulatively applied to,
and initial is the optional value that gets placed before the elements of the iterable in the calculation,
and serves as a default when the iterable is empty.
Notes Prepared by: P.Pooja , Assistant Professor, Dept of IT, GMRIT
Note: func requires two arguments, the first of which is the first element in iterable (if initial is not
supplied) and the second element in iterable. If initial is supplied, then it becomes the first argument
to func and the first element in iterable becomes the second element.

reduce() is a bit harder to understand than map() and filter(), so let's look at a step by step example:
• We start with a list [2, 4, 7, 3] and pass the add(x, y) function to reduce() alongside this
list, without an initial value
• reduce() calls add(2, 4), and add() returns 6
• reduce() calls add(6, 7) (result of the previous call to add() and the next element in the
list as parameters), and add() returns 13
• reduce() calls add(13, 3), and add() returns 16
• Since no more elements are left in the sequence, reduce() returns 16

The only difference, if we had given an initial value would have been an additional step,
where reduce() would call add(initial, 2) and use that return value in step 2.

Example 1:

from functools import reduce


def add(x, y):
return x + y
list = [2, 4, 7, 3]
print(reduce(add, list))

Output: 16

Reduce() function with Lambda:

Functions with no name are known as lambda functions. These functions are frequently used as

input to other functions. Let’s try to integrate Lambda functions into the reduce() function.

Example 2: from functools import reduce


reduce(lambda a,b: a+b,[23,21,45,98])

Output: 187

***

Notes Prepared by: P.Pooja , Assistant Professor, Dept of IT, GMRIT


Lecture Notes-23 Python Programming

Map
Map, Filter, and Reduce are paradigms of functional programming. They allow the programmer to
write simpler, shorter code, without necessarily needing to bother about intricacies like loops and
branching.

Essentially, these three functions allows to apply a function across a number of iterables, in one fell
swoop. Map and filter come built-in with Python and require no importing. Reduce, however, needs
to be imported as it resides in the functools module.

Map():

The map() function is a higher-order function. This function accepts another function and a
sequence of ‘iterables’ as parameters and provides output after applying the function to each iterable
in the sequence.
The map() function iterates through all items in the given iterable and executes the function we
passed as an argument on each of them.
Syntax:
map (func, * iterable(s))
Where func is the function on which each element in iterables would be applied on. Notice the
asterisk (*) on iterables? It means there can be as many iterables as possible, in so far func has that
exact number as required input arguments.
Example:

def starts_with_A(s) :
Return s[0] == “A”
Fruit = [“Apple”, “Banana”, “Orange”, “Mango”, “Grape”]
Map_object = map(starts_with_A, Fruit)
Print(list(map_object))

Output: [True, False, False, False, False]

Example 2:
def function(a):
return a*a
x = map(function, (1,2,3,4)) #x is the map object

Notes Prepared by: P.Pooja , Assistant Professor, Dept of IT, GMRIT


print(x)
print(set(x))

Output: {16, 1, 4, 9}

Example 3:
my_pets = ['alfred', 'tabitha', 'william', 'arla']
uppered_pets = list(map(str.upper, my_pets))
print(uppered_pets)

Output: ['ALFRED', 'TABITHA', 'WILLIAM', 'ARLA']

Lambda within map() functions:

Functions with no name are known as lambda functions. These functions are frequently used as

input to other functions. Let’s try to integrate Lambda functions into the map() function.

Example: tup= (5, 7, 22, 97, 54, 62, 77, 23, 73, 61)

newtuple = tuple(map(lambda x: x+3 , tup))


print(newtuple)
Output: (8, 10, 25, 100, 57, 65, 80, 26, 76, 64)

***

Notes Prepared by: P.Pooja , Assistant Professor, Dept of IT, GMRIT


Lecture Notes-24 Python Programming
Functions- Defining Functions, Calling Functions, Types of Arguments

Function: A function is a block of code which only runs when it is called. A function can acc
ept parameters as input and returns the output.

Defining a function:

Python uses a keyword “def” to create a function

def my_function():
print("Hello ! This is J Section")

Calling a Function:

def my_function():
print("Hello ! This is J Section ")

my_function()

Output: Hello ! This is J Section

Types of Function in Python:

a) Built in Functions #Refer Notes Number 20 in LAN.


b) User Defined Functions- Arguments or Parameters- Global vs Local Varaibles
c) Anonymous Functions
d) Using main() Function

Arguments (or) Parameters

Information can be passed into functions as arguments. Arguments are specified after the fun
ction name, inside the parentheses. N Number of arguments are taken separated with a semi-
colon.
• Default arguments
• Required arguments
• Keyword arguments
• Variable number of arguments

Example:
def my_function(Input):
print(Input + " Says Hello")
my_function("Prasad")

Notes Prepared by : Dr V Prasad, Associate Professor, Dept of CSE, GMRIT


my_function("Rajesh")
my_function("Abhinav")

Output:

Prasad Says Hello


Rajesh Says Hello
Abhinav Says Hello

Note: Function can take N parameters, but when a function is given with N parameters, all th
e N should definitely considered.

Function with Two Arguments:

def my_function(fname, lname):


print(fname + " " + lname)

my_function("Prasad", "Vadamodula")

Output: Prasad Vadamodula

Arbitrary Arguments, *args

Multiple arguments can be added using add a * before the parameter name in the function de
finition.

This way the function will receive a tuple of arguments, and can access the items accordingly
:

Example:
def my_function(*JSection):
print("The youngest child is " + JSection[3])

my_function("Prasad", "Abhinav", "Jaswanth", "Srinu")

Output: The youngest child is Srinu

Keyword Arguments

Arguments /Parameters can be sent in the format key= value.

Example:
def my_function(child3, child2, child1):
print("The youngest child is " + child3)

my_function(child1 = "Jaswanth", child2 = "Abhisekh", child3 = "Amrutha")

Notes Prepared by : Dr V Prasad, Associate Professor, Dept of CSE, GMRIT


Output: The youngest child is Amrutha

Arbitrary Keyword Arguments, **kwargs

Many keyword arguments that will be passed into the function, add two asterisk: ** before th
e parameter name in the function definition.

def my_function(**JSection):
print("His last name is " + JSection["lname"])

my_function(fname = "Vamsi", lname = "Varanasi")

Output: His last name is Varanasi

Default Parameter Value

The following example shows how to use a default parameter value. One keyword with One
Value.

Example:
def my_function(country = "Norway"):
print("I am from " + country)

my_function("Sweden")
my_function("India")
my_function()
my_function("Brazil")

Output:

I am from Sweden
I am from India
I am from Norway
I am from Brazil

Passing a List as an Argument

Assign and send any data types of argument to a function (string, number, list, dictionary etc.
), and it will be treated as the same data type inside the function.

Example:
def my_function(food):
for x in food:
print(x)

fruits = ["apple", "banana", "cherry"]

my_function(fruits)

Notes Prepared by : Dr V Prasad, Associate Professor, Dept of CSE, GMRIT


Output:

apple
banana
cherry

Return Values

To let a function return a value, use the return statement:

Example:
def my_function(x):
return 5 * x

print(my_function(3))
print(my_function(5))
print(my_function(9))

Output:
15
25
45

The pass Statement

Function definitions cannot be empty, but if for some reason;wanted a function definition wit
h no content, put in the pass statement to avoid getting an error.

Example:
def myfunction():
pass

Output: Blank Terminal

Note:
# having an empty function definition like this, would raise an error without the pass stateme
nt

Recursion
Python also accepts function recursion, which means a defined function can call itself. It mea
ns that a function calls itself.

Example:
def tri_recursion(k):
if(k > 0):
result = k + tri_recursion(k - 1)

Notes Prepared by : Dr V Prasad, Associate Professor, Dept of CSE, GMRIT


print(result)
else:
result = 0
return result

print("\n\nRecursion Example Results")


tri_recursion(6)

Output:

Recursion Example Results


1
3
6
10
15
21

Explanation:

In this example, tri_recursion() is a function that we have defined to call itself ("recurse"). W
e use the k variable as the data, which decrements (-1) every time we recurse. The recursion e
nds when the condition is not greater than 0 (i.e. when it is 0).

***

Notes Prepared by : Dr V Prasad, Associate Professor, Dept of CSE, GMRIT


Lecture Notes-25 Python Programming
• Anonymous Functions,
• Scope of the Variables in a Function Global and Local Variables.
Anonymous functions are also called lambda functions in Python because instead of declarin
g them with the standard def keyword, you use the lambda keyword.
• A lambda function is a small anonymous function.
• A lambda function can take any number of arguments, but can only have one expressi
on.
Syntax:
lambda arguments : expression
Example :
Add 10 to argument a, and return the result:
x = lambda a : a + 10
print(x(5))
Output: 15

Lambda functions can take any number of arguments:


Multiply argument a with argument b and return the result:
Example :
x = lambda a, b : a * b
print(x(5, 6))
Output: 30
Summarize argument a, b, and c and return the result:
Example :
x = lambda a, b, c : a + b + c
print(x(5, 6, 2))
Output: 13

Power of lambda is better shown when you use them as an anonymous function inside a
nother function.

def myfunc(n):
return lambda a : a * n

Notes Prepared by : Dr V Prasad, Associate Professor, Dept of CSE, GMRIT


Use that function definition to make a function that always doubles the number
Example:
def myfunc(n):
return lambda a : a * n
mydoubler = myfunc(2)
print(mydoubler(11))
Output: 22

Use the same function definition to make a function that always triples the number

Example:
def myfunc(n):
return lambda a : a * n
mytripler = myfunc(3)
print(mytripler(11))
Output: 33

Use the same function definition to make both functions, in the same program

Example:
def myfunc(n):
return lambda a : a * n
mydoubler = myfunc(2)
mytripler = myfunc(3)
print(mydoubler(11))
print(mytripler(11))
Output:
22
33

Notes Prepared by : Dr V Prasad, Associate Professor, Dept of CSE, GMRIT


Scope of variable

The location where a variable is found and also cab be accessed it if required is called the sc
ope of a variable.

Global and local variables:

Global variables are the ones that are defined and declared outside any function and are not s
pecified to any function. They can be used by any part of the program.
Example:
# This function uses global variable s
def f():
print(s)

# Global scope
s = "I love GMRIT"
f()
Output: I love GMRIT

Example 2:
# This function has a variable with
# name same as s.
def f():
s = "Me too."
print(s)

# Global scope
s = "I love GMRIT"
f()
print(s)
Output:

Me too.
I love GMRIT

Notes Prepared by : Dr V Prasad, Associate Professor, Dept of CSE, GMRIT


Example 3:
# This function modifies global variable 's'
def f():
global s
print(s)
s = "Look for J Section Python"
print(s)

# Global Scope
s = "Python is great !"
f()
print(s)

Output:
Python is great!
Look for J Section Python
Look for J Section Python

Example 4:
# Python program to demonstrate
# scope of variable
a=1
# Uses global because there is no local 'a'
def f():
print('Inside f() : ', a)
# Variable 'a' is redefined as a local
def g():
a=2
print('Inside g() : ', a)
# Uses global keyword to modify global 'a'
def h():
global a
a=3

Notes Prepared by : Dr V Prasad, Associate Professor, Dept of CSE, GMRIT


print('Inside h() : ', a)
# Global scope
print('global : ', a)
f()
print('global : ', a)
g()
print('global : ', a)
h()
print('global : ', a)

Output:
global : 1
Inside f() : 1
global : 1
Inside g() : 2
global : 1
Inside h() : 3
global : 3

Nonlocal keyword
In Python, nonlocal keyword is used in the case of nested functions. This keyword works sim
ilar to the global, but rather than global, this keyword declares a variable to point to the varia
ble of outside enclosing function, in case of nested functions.

# Python program to demonstrate


# nonlocal keyword
print ("Value of a using nonlocal is : ", end ="")
def outer():
a=5
def inner():
nonlocal a
a = 10
inner()
print (a)

Notes Prepared by : Dr V Prasad, Associate Professor, Dept of CSE, GMRIT


outer()
# demonstrating without non local
# inner loop not changing the value of outer a
# prints 5
print ("Value of a without using nonlocal is : ", end ="")
def outer():
a=5
def inner():
a = 10
inner()
print (a)

outer()

Output:
Value of a using nonlocal is : 10
Value of a without using nonlocal is : 5
***

Notes Prepared by : Dr V Prasad, Associate Professor, Dept of CSE, GMRIT


Lecture Notes-26 Python Programming
Modules and Packages: Creating and Working on Modules
Module:
A file containing a set of functions which includes in an application is known as Module.
Modules refer to a file containing Python statements and definitions.
A file containing Python code, for example: example.py, is called a module, and its module
name would be example.
Modules are used to break down large programs into small manageable and organized files.
Furthermore, modules provide reusability of code.
Define the most used functions in a module and import it, instead of copying their definitions
into different programs.
Create a Module:
example.py.
# Python Module example
def add(a, b):
#"This program adds two numbers and return the result"
result = a + b
return result
Here, we have defined a function add() inside a module named example. The function takes
in two numbers and returns their sum.
Importing modules
Import the definitions inside a module to another module or the interactive interpreter in
Python.
The import keyword used for the same. To import our previously defined module example,
we type the following in the Python prompt.
import example
This does not import the names of the functions defined in example directly in the current
symbol table. It only imports the module name example there.
Using the module name we can access the function using the dot (.) operator.
For example:
example.add(4,5.5)
Output:
9.5

Notes Prepared by: Ms. Santhoshini Sahu, Assistant Professor, Dept of CSE, GMRIT
Example:
• Save this code in a file named modules.py
def greeting(name):
print("Hello, " + name)
• Import the module named modules, and call the greeting function:
import modules
modules.greeting(“Python”)
Output:
Hello, Python
Variables in Module
The module can contain functions, as already described, but also variables of all types
(arrays, dictionaries, objects etc):
Example
Save this code in the file modules.py
person1 = {
"name": "John",
"age": 16,
"country": "India"
}

Import the module named modules, and access the person1 dictionary:
import modules
a = modules.person1["age"]
print(a)
Output:
16

Naming a Module
You can name the module file whatever you like, but it must have the file extension .py
Re-naming a Module
You can create an alias when you import a module, by using the as keyword:

Notes Prepared by: Ms. Santhoshini Sahu, Assistant Professor, Dept of CSE, GMRIT
Example
Create an alias for modules called mx:
import modules as mx
a = mx.person1["age"]
print(a)
Output:
36

Built-in Modules
There are several built-in modules in Python, which you can import whenever you like.
Import and use the platform module:
import platform
x = platform.system()
print(x)
Output:
Windows

Using the dir() Function


There is a built-in function to list all the function names (or variable names) in a module. The
dir() function:
Example
List all the defined names belonging to the platform module:
import platform
x = dir(platform)
print(x)
Output:
['DEV_NULL', '_UNIXCONFDIR', '_WIN32_CLIENT_RELEASES',
'_WIN32_SERVER_RELEASES', '__builtins__', '__cached__', '__copyright__', '__doc__',
'__file__', '__loader__', '__name__', '__package__', '__spec__', '__version__',
'_comparable_version', '_component_re', '_default_architecture', '_dist_try_harder',
'_follow_symlinks', '_ironpython26_sys_version_parser', '_ironpython_sys_version_parser',
'_java_getprop', '_libc_search', '_linux_distribution', '_lsb_release_version', '_mac_ver_xml',
'_node', '_norm_version', '_parse_release_file', '_platform', '_platform_cache',

Notes Prepared by: Ms. Santhoshini Sahu, Assistant Professor, Dept of CSE, GMRIT
'_pypy_sys_version_parser', '_release_filename', '_release_version', '_supported_dists',
'_sys_version', '_sys_version_cache', '_sys_version_parser', '_syscmd_file', '_syscmd_uname',
'_syscmd_ver', '_uname_cache', '_ver_output', '_ver_stages', 'architecture', 'collections', 'dist',
'java_ver', 'libc_ver', 'linux_distribution', 'mac_ver', 'machine', 'node', 'os', 'platform', 'popen',
'processor', 'python_branch', 'python_build', 'python_compiler', 'python_implementation',
'python_revision', 'python_version', 'python_version_tuple', 're', 'release', 'subprocess', 'sys',
'system', 'system_alias', 'uname', 'uname_result', 'version', 'warnings', 'win32_ver']

***

Notes Prepared by: Ms. Santhoshini Sahu, Assistant Professor, Dept of CSE, GMRIT
Lecture Notes-27 Python Programming
Import statements from import modules
Python's from statement gives import specific attributes from a module into the current
namespace.
The from...import has the following syntax
from modname import name1[, name2[, ... nameN]]
For example, to import the function fib from the module fibonacc, use the following
statement:
from fibonacc import fib
This statement does not import the entire module fib into the current namespace; it just
introduces the item fib from the module fibonacc into the global symbol table of the
importing module.
The from...import * Statement
It is also possible to import all names from a module into the current namespace by using the
following import statement
from module_name import *
This provides an easy way to import all the items from a module into the current namespace;
however, this statement should be used sparingly.
Example:
# Fibonacci numbers module
def fib(n): # write Fibonacci series up to n
a, b = 0, 1
while b < n:
print(b, end=' ')
a, b = b, a+b
print()
def fib2(n): # return Fibonacci series up to n
result = []
a, b = 0, 1
while b < n:
result.append(b)
a, b = b, a+b

Notes Prepared by: Ms. Santhoshini Sahu, Assistant Professor, Dept of CSE, GMRIT
return result
Save the above code as “fibonacc.py”.
Now enter the Python interpreter and import this module with the following command:
import fibonacc
This does not enter the names of the functions defined in fibonacc directly in the current
symbol table; it only enters the module name fibonacc there. Using the module name you can
access the functions:
fibonacc.fib(1000)
Output:
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987
fibonacc.fib2(100)
Output:
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
fibonacc.__name__
Output:
' fibonacc '
If you intend to use a function often you can assign it to a local name:
fib = fibonacc.fib
fib(500)
Output:
1 1 2 3 5 8 13 21 34 55 89 144 233 377
There is even a variant to import all names that a module defines:
from fibonacc import *
fib(500)
fib2(200)
1 1 2 3 5 8 13 21 34 55 89 144 233 377
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144]

***

Notes Prepared by: Ms. Santhoshini Sahu, Assistant Professor, Dept of CSE, GMRIT
Lecture Notes-27 Python Programming
Math Modules
Python has a built-in module that can be used for mathematical tasks.
The math module has a set of methods and constants.
Math Methods:
Method Description
math.acos() Returns the arc cosine of a number
math.acosh() Returns the inverse hyperbolic cosine of a number
math.asin() Returns the arc sine of a number
math.asinh() Returns the inverse hyperbolic sine of a number
math.atan() Returns the arc tangent of a number in radians
math.atan2() Returns the arc tangent of y/x in radians
math.atanh() Returns the inverse hyperbolic tangent of a number
math.ceil() Rounds a number up to the nearest integer
math.copysign() Returns a float consisting of the value of the first parameter and the sign of the
second parameter
math.cos() Returns the cosine of a number
math.cosh() Returns the hyperbolic cosine of a number
math.degrees() Converts an angle from radians to degrees
math.dist() Returns the Euclidean distance between two points (p and q), where p and q are
the coordinates of that point
math.erf() Returns the error function of a number
math.erfc() Returns the complementary error function of a number
math.exp() Returns E raised to the power of x
math.expm1() Returns Ex - 1
math.fabs() Returns the absolute value of a number
math.factorial() Returns the factorial of a number
math.floor() Rounds a number down to the nearest integer
math.fmod() Returns the remainder of x/y
math.frexp() Returns the mantissa and the exponent, of a specified number
math.fsum() Returns the sum of all items in any iterable (tuples, arrays, lists, etc.)
math.gamma() Returns the gamma function at x
math.gcd() Returns the greatest common divisor of two integers
math.hypot() Returns the Euclidean norm
math.isclose() Checks whether two values are close to each other, or not
math.isfinite() Checks whether a number is finite or not
math.isinf() Checks whether a number is infinite or not
math.isnan() Checks whether a value is NaN (not a number) or not
math.isqrt() Rounds a square root number downwards to the nearest integer
math.ldexp() Returns the inverse of math.frexp() which is x * (2**i) of the given numbers x
and i
math.lgamma() Returns the log gamma value of x
math.log() Returns the natural logarithm of a number, or the logarithm of number to base
math.log10() Returns the base-10 logarithm of x
math.log1p() Returns the natural logarithm of 1+x
math.log2() Returns the base-2 logarithm of x
math.perm() Returns the number of ways to choose k items from n items with order and

Notes Prepared by: Ms. Santhoshini Sahu, Assistant Professor, Dept of CSE, GMRIT
without repetition
math.pow() Returns the value of x to the power of y
math.prod() Returns the product of all the elements in an iterable
math.radians() Converts a degree value into radians
math.remainder() Returns the closest value that can make numerator completely divisible by the
denominator
math.sin() Returns the sine of a number
math.sinh() Returns the hyperbolic sine of a number
math.sqrt() Returns the square root of a number
math.tan() Returns the tangent of a number
math.tanh() Returns the hyperbolic tangent of a number
math.trunc() Returns the truncated integer parts of a number

Math Constants
Constant Description
math.e Returns Euler's number (2.7182...)
math.inf Returns a floating-point positive infinity
math.nan Returns a floating-point NaN (Not a Number) value
math.pi Returns PI (3.1415...)
math.tau Returns tau (6.2831...)

math.acos() Method
The math.acos() method returns the arc cosine value of a number.
Note: The parameter passed in math.acos() must lie between -1 to 1.
Tip: math.acos(-1) will return the value of PI.
Syntax:
math.acos(x)
Example:
# Import math Library
import math
# Return the arc cosine of numbers
print(math.acos(0.55))
print(math.acos(-0.55))
print(math.acos(0))
print(math.acos(1))
print(math.acos(-1))
Output:

Notes Prepared by: Ms. Santhoshini Sahu, Assistant Professor, Dept of CSE, GMRIT
0.9884320889261531
2.15316056466364
1.5707963267948966
0.0
3.141592653589793
math.ceil() Method
The math.ceil() method rounds a number UP to the nearest integer, if necessary, and returns
the result.
Tip: To round a number DOWN to the nearest integer, look at the math.floor() method.
Syntax:
math.ceil(x)
Example:
# Import math library
import math
# Round a number upward to its nearest integer
print(math.ceil(1.4))
print(math.ceil(5.3))
print(math.ceil(-5.3))
print(math.ceil(22.6))
print(math.ceil(10.0))
Output:
2
6
-5
23
10
math.fabs() Method
The math.fabs() method returns the absolute value of a number, as a float.
Absolute denotes a non-negative number. This removes the negative sign of the value if it has
any.
Unlike Python abs(), this method always converts the value to a float value.

Notes Prepared by: Ms. Santhoshini Sahu, Assistant Professor, Dept of CSE, GMRIT
Syntax:
math.fabs(x)
Example:
#Import math Library
import math
#Print absolute values from numbers
print(math.fabs(-66.43))
print(math.fabs(-7))
Output:
66.43
7.0
math.factorial() Method
The math.factorial() method returns the factorial of a number.
Note: This method only accepts positive integers.
The factorial of a number is the sum of the multiplication, of all the whole numbers, from our
specified number down to 1. For example, the factorial of 6 would be 6 x 5 x 4 x 3 x 2 x 1 =
720
Syntax:
math.factorial(x)
Example:
#Import math Library
import math
#Return factorial of a number
print(math.factorial(9))
print(math.factorial(6))
print(math.factorial(12))
Output:
362880
720
479001600

Notes Prepared by: Ms. Santhoshini Sahu, Assistant Professor, Dept of CSE, GMRIT
math.floor() Method
The math.floor() method rounds a number DOWN to the nearest integer, if necessary, and
returns the result.
Tip: To round a number UP to the nearest integer, look at the math.ceil() method.
Syntax:
math.floor(x)
Example:
# Import math library
import math
# Round numbers down to the nearest integer
print(math.floor(0.6))
print(math.floor(1.4))
print(math.floor(5.3))
print(math.floor(-5.3))
print(math.floor(22.6))
print(math.floor(10.0))
Output:
0
1
5
-6
22
10
math.gcd() Method
The math.gcd() method returns the greatest common divisor of the two integers int1 and int2.
GCD is the largest common divisor that divides the numbers without a remainder.
GCD is also known as the highest common factor (HCF).
Tip: gcd(0,0) returns 0.
Syntax:
math.gcd(int1, int2)

Notes Prepared by: Ms. Santhoshini Sahu, Assistant Professor, Dept of CSE, GMRIT
Example:
#Import math Library
import math
#find the the greatest common divisor of the two integers
print (math.gcd(3, 6))
print (math.gcd(6, 12))
print (math.gcd(12, 36))
print (math.gcd(-12, -36))
print (math.gcd(5, 12))
print (math.gcd(10, 0))
print (math.gcd(0, 34))
print (math.gcd(0, 0))
Output:
3
6
12
12
1
10
34
0
math.pow() Method
The math.pow() method returns the value of x raised to power y.
If x is negative and y is not an integer, it returns a ValueError.
This method converts both arguments into a float.
Tip: If we use math.pow(1.0,x) or math.pow(x,0.0), it will always returns 1.0.
Syntax:
math.pow(x, y)
Example:
# Import math Library

Notes Prepared by: Ms. Santhoshini Sahu, Assistant Professor, Dept of CSE, GMRIT
import math
#Return the value of 9 raised to the power of 3
print(math.pow(9, 3))
Output:
729.0
math.sqrt() Method
The math.sqrt() method returns the square root of a number.
Note: The number must be greater than or equal to 0.
Syntax:
math.sqrt(x)
Example:
# Import math Library
import math
# Return the square root of different numbers
print (math.sqrt(9))
print (math.sqrt(25))
print (math.sqrt(16))
Output:
3.0
5.0
4.0
math.pi Constant
The math.pi constant returns the value of PI: 3.141592653589793.
Note: Mathematically PI is represented by π.
Example:
# Import math Library
import math
# Print the value of pi
print (math.pi)
Output:

Notes Prepared by: Ms. Santhoshini Sahu, Assistant Professor, Dept of CSE, GMRIT
3.141592653589793

***

Notes Prepared by: Ms. Santhoshini Sahu, Assistant Professor, Dept of CSE, GMRIT
Lecture notes-29 Python Programming

Itertools

Itertools is one of the most useful modules in Python. Python Itertools is a module that
provides various functions that work on iterators to produce complex iterators. Its functions
make it a breeze to work with lists and arrays.
Python Itertools is a library in Python generally consisting of multiple methods. These are
used in various iterators to compute a fast and code efficient solution in the runtime.
itertools. product() is a part of a python module itertools; a collection of tools used to handle
iterators. Together all these tools form iterator algebra.

Syntax: import itertools


# or can directly import
from itertools import product

There are three different types of itertools. They are:

1. Infinite itertools: These type of iterators produce infinite sequences.(count(),


cycle(), repeat())
2. Combinatoric itertools: These generators produce the sequences in combinations
related to the input arguments.(product(), permutations(), combinations(),
combinations_with_replacement())
3. Terminating iterators on the shortest input sequence: These iterators produces
the sequences which terminate after certain iterations.(accumulate(), chain(),
compress(), dropwhile(), filterfalse(), zip_longest() etc.)

Infinite itertools
Python iterators like lists, tuples, and dictionaries are exhaustive. But it is not necessary for
an iterator to exhaust at some point, they can go on forever. Infinite iterators can run a loop
infinitely. These functions more often run using a for loop. There are three infinite iterators:

1) count(start, step): count() may take two values- start and step. This iterator starts
returning values from ‘start’ and goes on infinitely, if steps are provided then those
values are skipped. If you are not given start value by default, it returns a from 0.

Syntax: itertools.count(start, step)

Notes Prepared by: Mrs. P. Padmavathi, Assistant Professor, Dept. of IT, GMRIT
Ex1: for i in itertools.count(2,2):
if i == 10:
break
else:
print(i, end=" ")
Output:
2 4 6 8

Ex2: from itertools import count


for i in count(10,2):
print(i)
if i>17: break
Output: 10
12
14
16

2) repeat(value, timesToRepeat): This iterator repeatedly prints the passed value an


infinite number of times. The repeat() function accepts two parameters. The first is a
value that the function produces repeatedly. The second parameter is the number of
times the number should repeat. If you don't specify the second parameter, the loop
will run infinitely.

Syntax: itertools.repeat (value, timesToRepeat)

Ex1: for i in itertools.repeat (‘Itertools’,2):


print(i)
Output: Itertools
Itertools

Ex2: from itertools import repeat


for i in repeat(‘python’,3):
print(i)
Output: python
python
python

3) cycle(input): The cycle() function iterates through the input and prints individual
items in a given order. When it reaches the end of its input, cycle restarts from the
beginning.

Syntax: itertools.cycle(input)

Ex1:
c=0
var = "12345"

Notes Prepared by: Mrs. P. Padmavathi, Assistant Professor, Dept. of IT, GMRIT
for i in itertools.cycle(var):
if c == 12:
break
else:
c=c+1
print(i, end=" ")
Output: 1 2 3 4 5 1 2 3 4 5 1 2

***

Notes Prepared by: Mrs. P. Padmavathi, Assistant Professor, Dept. of IT, GMRIT
Lecture notes-30 Python Programming

Itertools

Combinatoric itertools
The combinatoric iterators provide functions to perform permutations, combinations, and
cartesian products. In Python there are 3 combinatoric iterators:

1) product (input): product() returns the cartesian product of the input iterables. This is
equivalent to a nested for-loop. To compute the product of an iterable with itself, we
use the optional repeat keyword argument to specify the number of repetitions.

Syntax: Itertools.product(input)

Ex1: array = [1,2,3]


print(list(itertools.product(array, repeat=2)))

Output: [(1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3), (3, 1), (3, 2), (3, 3)]

Ex2: from itertools import product


string = "ABC"
print(list(product(string, "XYZ")))
Output: [('A', 'X'), ('A', 'Y'), ('A', 'Z'), ('B', 'X'), ('B', 'Y'), ('B', 'Z'), ('C', 'X'), ('C', 'Y'),
('C', 'Z')]

2) permutations(input, size): This function returns a tuple of all the permutations of the
given iterable. permutations() returns size permutations of elements in the input. It
accepts two parameters: the iterable and group size. If the group size is not specified,
it will form groups of the same length as the iterable itself.

Syntax: Itertools.permutations(input, size)

Ex1: from itertools import permutations


for i in permutations('ABC'):
print(i)
Output: ('A', 'B', 'C')
('A', 'C', 'B')
('B', 'A', 'C')
('B', 'C', 'A')
('C', 'A', 'B')
('C', 'B', 'A')

Ex2: arr = [1,2,3,4]


print(list(itertools.permutations(arr, 2)))
Output:

Notes Prepared by: Mrs. P. Padmavathi, Assistant Professor, Dept. of IT, GMRIT
[(1, 2), (1, 3), (1, 4), (2, 1), (2, 3), (2, 4), (3, 1), (3, 2), (3, 4), (4, 1), (4, 2), (4, 3)]

3) Combinations (input, length): The combinations () function helps to compute the


combinations of the given iterator. This returns subsequence’s of length from the
elements of the input. Note that this function maintains the item order of its input.
While a permutation includes values that differ only by order, combinations produce
unique values.

Syntax: Itertools.combinations(input, length)

Ex1: arr = [1,2,3,4]


print(list(itertools.combinations(arr, 3)))
Output: [(1, 2, 3), (1, 2, 4), (1, 3, 4), (2, 3, 4)]
Ex2: from itertools import combinations
for i in combinations('ABCD',2):
print(i)

Output: (‘A’, ‘B’)


(‘A’, ‘C’)
(‘A’, ‘D’)
(‘B’, ‘C’)
(‘B’, ‘D’)
(‘C’, ‘D’)

4) combinations_with_replacement(): As understood by name “combinations” means


all the possible subsets or arrangements of the iterator and the word
“combinations_with_replacement” means all the possible arrangements or subsets
that allow an element to repeat in a subset. This one is just like
the combinations() function, but this one allows individual elements to be repeated
more than once.

Syntax:itertools.combinations_with_replacement(iterable, r)

Ex: shapes = ['circle', 'triangle', 'square',]


result = itertools.combinations_with_replacement(shapes, 2)
for each in result:
print(each)
Output:
('circle', 'circle')
('circle', 'triangle')
('circle', 'square')
('triangle', 'triangle')
('triangle', 'square')
('square', 'square')

Notes Prepared by: Mrs. P. Padmavathi, Assistant Professor, Dept. of IT, GMRIT
Terminating iterators on the shortest input sequence :
These iterators are used to work on finite sequences and produce an output based on the
function used.

1) chain(*iterables): chain() makes an iterator from elements of the first iterable, then
from the second, and so on.

Syntax: itertools.chain(*iterables)

Ex1: from itertools import chain


for i in chain('Hello','World'):
print(i)
Output:
H
e
l
l
o
W
o
r
l
d

Ex2: from itertools import chain


for I in chain([0,1,2,3], range(4,11), ‘ABC’):
print(I, end = ‘ ’)
Output: 0 1 2 3 4 5 6 7 8 9 10 A B C

2) compress(data, selectors): This makes an iterator that filters elements, from data, for
which selector values amount to True.

Syntax: Itertools. compress(data, selectors)

Ex1: from itertools import compress


for i in compress('ABCDEF',[1,0,1,True,0,' ']) :
print(i)
Output: A
C
D
F

3) groupby(iterable,key=None): This makes an iterator that takes the iterable, and


returns consecutive keys and groups. These are sub-iterators grouped by the key.

Syntax: Itertools.groupby(iterable,key=None)

Notes Prepared by: Mrs. P. Padmavathi, Assistant Professor, Dept. of IT, GMRIT
Ex1: from itertools import groupby
for i,j in groupby('AAAAABBCCCCCDDDCCCBBA') :
print(list(j))
Output: [‘A’, ‘A’, ‘A’, ‘A’, ‘A’]
[‘B’, ‘B’]
[‘C’, ‘C’, ‘C’, ‘C’, ‘C’]
[‘D’, ‘D’, ‘D’]
[‘C’, ‘C’, ‘C’]
[‘B’, ‘B’]
[‘A’]

***

Notes Prepared by: Mrs. P. Padmavathi, Assistant Professor, Dept. of IT, GMRIT
Lecture Notes-31 Python Programming

Files: Creating files, operations on files

File

A file is a container that stores data. As files are non-volatile in nature, the data will be stored
permanently in a secondary device like Hard Disk and using python we will handle these files
in our applications.

Types of Files in Python:


There are two types of files in Python. They are:
• Binary file
• Text file

Binary files: Most of the files that we see in our computer system are called binary files.
• Document files: .pdf, .doc, .xls etc.
• Image files: .png, .jpg, .gif, .bmp etc.
• Video files: .mp4, .3gp, .mkv, .avi etc.
• Audio files: .mp3, .wav, .mka, .aac etc.
• Database files: .mdb, .accde, .frm, .sqlite etc.
• Archive files: .zip, .rar, .iso, .7z etc.
• Executable files: .exe, .dll, .class etc.

Text files: Text files don’t have any specific encoding and it can be opened in normal text
editor itself.
• Web standards: html, XML, CSS, JSON etc.
• Source code: c, app, js, py, java etc.
• Documents: txt, tex, RTF etc.
• Tabular data: csv, tsv etc.
• Configuration: ini, cfg, reg etc.

Python File Handling Operations:


Most importantly there are 4 types of operations that can be handled by Python on files:
• Open
• Read
• Write
• Close

Creating and Opening a File:


Python has an in-built function called open () to create and open a file.
It takes a minimum of one argument as mentioned in the below syntax. The open method
returns a file object which is used to access the write, read and other in-built methods.

Notes Prepared by: Mrs. P. Padmavathi, Assistant Professor, Dept. of IT, GMRIT
Syntax: file_object = open(file_name, mode)
Here, file_name is the name of the file or the location of the file that you want to open, and
file_name should have the file extension included as well. Which means in mydocument.txt –
the term mydocument is the name of the file and .txt is the extension of the file. The mode in
the open function syntax will tell Python as what operation you want to do on a file. The
following example gives an idea about creating a file at a specified path
Ex: f = open("f:\mydocument.txt","w")
f.write("python programming")
f.close()

Access modes:

• ‘r’ – Read Mode: Read mode is used only to read data from the file.
• ‘w’ – Write Mode: This mode is used when you want to write data into the file or
modify it. Remember write mode overwrites the data present in the file.
• ‘a’ – Append Mode: Append mode is used to append data to the file. Remember
data will be appended at the end of the file pointer.
• ‘r+’ – Read or Write Mode: This mode is used when we want to write or read the
data from the same file.
• ‘a+’ – Append or Read Mode: This mode is used when we want to read data from
the file or append the data into the same file.

The above-mentioned modes are for opening, reading or writing text files only.
While using binary files, we have to use the same modes with the letter ‘b’ at the end. So that
Python can understand that we are interacting with binary files.
• ‘wb’ – Open a file for write only mode in the binary format.
• ‘rb’ – Open a file for the read-only mode in the binary format.
• ‘ab’ – Open a file for appending only mode in the binary format.
• ‘rb+’ – Open a file for read and write only mode in the binary format.
• ‘ab+’ – Open a file for appending and read-only mode in the binary format.

Notes Prepared by: Mrs. P. Padmavathi, Assistant Professor, Dept. of IT, GMRIT
Example 1:

fo = open(“C:/Documents/Python/test.txt”, “r+”)
In the above example, we are opening the file named ‘test.txt’ present at the location
‘C:/Documents/Python/’ and we are opening the same file in a read-write mode which gives us
more flexibility.
Reading a File:
In order to read a file in python, we must open the file in read mode. There are three ways
in which we can read the files in python.
• read()
• read(n)
• readline()
• readlines()
Here, n is the number of bytes to be read.
let’s create a sample text file as shown below.
Ex:
f = open("f:\mydocument.txt","w")
f.write("python programming \n" \
"c programming \n" \
"object oriented programming")
f.close()

the above ex.’s output is shown right side

Now let’s observe what each read method does:


1. read()
f = open("f:\mydocument.txt","r")
print(f.read())

output: python programming


c programming
object oriented programming

Notes Prepared by: Mrs. P. Padmavathi, Assistant Professor, Dept. of IT, GMRIT
2. read(n)
f = open("f:\mydocument.txt","r")
print(f.read(4))
output: pyth

3. readline()
f = open("f:\mydocument.txt","r")
print(f.readline())

output: python programming

4. readlines()
f = open("f:\mydocument.txt","r")
print(f.readlines())

output:
['python programming \t \n', 'c programming \n', 'object oriented programming']

Writing to a File:
In order to write data into a file, we must open the file in write mode.
We need to be very careful while writing data into the file as it overwrites the content present
inside the file that you are writing, and all the previous data will be erased.
We have two methods for writing data into a file as shown below.
• write(string)
• writelines(list)

1. write(string):

f = open("f:\mydocument.txt","w")
f.write("python programming")
f.close()

2. writelines(list):

fruits = ["Apple\n", "Orange\n", "Grapes\n"]


f = open("f:\mydocument.txt","w")
f.writelines(fruits)
f.close()

Notes Prepared by: Mrs. P. Padmavathi, Assistant Professor, Dept. of IT, GMRIT
Closing a File:
After completing our operations on the file, it is highly recommended to close the file. For this
we have to use close() function.
Syntax: f.close()

***

Notes Prepared by: Mrs. P. Padmavathi, Assistant Professor, Dept. of IT, GMRIT
Lecture Notes-32 Python Programming
Searching:
• Searching is a technique that helps in finding the position of a given element or value
in a list.
• If we find the element which we are searching, then we will say searching is
successful but we don’t found the element then we will say searching is not
successful.
• Searching is most prevalent task that we do in our daily life. Like searching contacts
list in mobile, student list in register.

Searching Techniques: There are mainly two types of searching techniques.


1) Linear Search
2) Binary Search

Linear Search: This is the simplest searching technique. It sequentially checks each element
of the list for the target searching value until a match is found or until all the elements have
been searched. This searching technique can be performed on both type of list, either the list
is sorted or unsorted.
• It is also known as sequential search.
• In this search technique, we start at the beginning of the list and search for the
searching element by examining each subsequent element until the searching element
is found or the list is exhausted.
• It is one of the simplest searching technique.
• This technique can be applied to both sorted and unsorted list.

Example: searching element using linear search

Notes Prepared by : Mrs A Vineela, Assistant Professor, Dept of CSE, GMRIT


Explanation:
• In this example we take an unsorted list which have 8 elements.
• 15 is our target element.
• Now we will see how the searching is happening.
• In first comparison we will compare target element with the element present at first
place. If both will match then we will return element found but in this example
element is not found at first place so we will move to the second comparison.
• In second comparison we will repeat the same procedure as we have done earlier.
• We will repeat this process until we find the target element.
• In this example we find the target element in 6th comparison. Now we will stop the
searching process and return the target element.
• The above process is depicted in this figure very clearly.

Program:
#defining function for linear search
def linear_search(mylist,item):
for i in range(len(mylist)):
if mylist[i]==item:
return i
return -1
#creating empty list and adding elements
mylist=[]
n=int(input('enter number of elements in list'))
for i in range(n):
mylist.append(int(input()))
print("list created is %s"%(mylist))

#searching element by calling function


print("Element in List :", mylist)
x = int(input("enter searching element :"))

#result
result = linear_search(mylist,x)
if result==-1:
print("Element not found in the list")
else:
print(f"Element {x} is found at position {result}")

Output 1:
enter number of elements in list6
12
35
62
2

Notes Prepared by : Mrs A Vineela, Assistant Professor, Dept of CSE, GMRIT


45
89
Element in List : [12, 35, 62, 2, 45, 89]
enter searching element :2
Element 2 is found at position 3

Output 2:
enter number of elements in list5
15
56
26
33
25
list created is [15, 56, 26, 33, 25]
Element in List : [15, 56, 26, 33, 25]
enter searching element :5
Element not found in the list

Linear Search Advantages:

• It is simplest and conventional searching technique.


• Linear search can be applied on both sorted or unsorted list of data.
• It is easy to implement.

Linear Search Disadvantages:

• If the list has large numbers of data then it is insufficient for searching data.
• It takes more time for searching data.
• If there are 200 elements in the list and you want to search element at the position 199
then you have to search the entire list, that’s consume time.

Notes Prepared by : Mrs A Vineela, Assistant Professor, Dept of CSE, GMRIT


Lecture Notes-33 Python Programming

Binary Search:
• Binary Search is a searching algorithm for finding an element's position in a sorted
array. Binary search algorithms are fast and effective in comparison to linear search
algorithms. The most important thing to note about binary search is that it works only
on sorted lists of elements.
• If the list is not sorted, then the algorithm first sorts the elements using the sorting
algorithm and then runs the binary search function to find the desired output.
• There are two methods by which we can run the binary search algorithm. They are:
1. Iterative method
2. Recursive method
• The steps of the process are general for both the methods; the difference is only found
in the function calling.
Iterative method: A set of statements is repeated multiple times to find an element's index
position in the iterative method. The while loop is used for accomplish this task.
Recursive method: The divide and conquer approach technique is followed by the recursive
method. In this method, a function is called itself again and again until it found an element in
the list.
Example: Searching element using Binary Search

Explanation:
1. In this example we take an sorted list which have 10 elements.
2. 23 is our target element.
3. Set two pointers low and high at the lowest and the highest positions respectively
4. Iteration 1: elements = 2, 5, 8, 12, 16, 23, 38, 56, 72, 91
• Select the middle element. (here 16)

Notes Prepared by: Mrs A Vineela, Assistant Professor, Dept of CSE, GMRIT
• Since 23 is greater than 16, so we divide the array into two halves and
consider the sub-array after element 16.
• Now this subarray with the elements after 16 will be taken into next iteration.
5. Iteration 2: elements= 23,38,56,72,91
• Select the middle element. (now 56)
• Since 23 is smaller than 56, so we divide the array into two halves and
consider the sub-array before element 56.
• Now this subarray with the elements before 56 will be taken into next
iteration.
6. Iteration 3: elements=23,38
7. Select the middle element. (now 23)
8. Since 23 is the middle element. So the iterations will now stop.
9. The above process is depicted in this figure very clearly.
Program: Iterative method
#Function declaration
def binarySearch(lst, x, low, high):
# Repeat until the pointers low and high meet each other
while low <= high:
mid = low + (high - low)//2
if lst[mid] == x:
return mid
elif lst[mid] < x:
low = mid + 1
else:
high = mid - 1
return -1

#creating Empty list and appending elements to list


lst = []
n=int(input('enter total element count in list:'))
for i in range(n):
lst.append(int(input()))
print('created list is',lst)

#input element to search


x = int(input('enter element to search:'))
result = binarySearch(lst, x, 0, len(lst)-1)
if result != -1:
print("Element is present at index " + str(result))
else:
print("Element not found")

Notes Prepared by: Mrs A Vineela, Assistant Professor, Dept of CSE, GMRIT
Output 1:
enter total element count in list:6
12
45
89
63
79
44
created list is [12, 45, 89, 63, 79, 44]
enter element to search:89
Element is present at index 2
Output 2:
enter total element count in list:5
14
56
2
35
89
created list is [14, 56, 2, 35, 89]
enter element to search:1
Element not found

Program: Recursive Method


# Binary Search in python
def binarySearch(lst, x, low, high):
if high >= low:
mid = low + (high - low)//2
# If found at mid, then return it
if lst[mid] == x:
return mid
# Search the left half
elif lst[mid] > x:
return binarySearch(lst, x, low, mid-1)
# Search the right half
else:
return binarySearch(lst, x, mid + 1, high)
else:
return -1
return -1

#creating Empty list and appending elements to list


lst = []
n=int(input('enter total element count in list:'))
for i in range(n):
lst.append(int(input()))
print('created list is',lst)

Notes Prepared by: Mrs A Vineela, Assistant Professor, Dept of CSE, GMRIT
#input element to search
x = int(input('enter element to search:'))
result = binarySearch(lst, x, 0, len(lst)-1)
if result != -1:
print("Element is present at index ",result)
else:
print("Element Not found")

Output 1:
enter total element count in list:6
12
13
6
41
52
63
created list is [12, 13, 6, 41, 52, 63]
enter element to search:41
Element is present at index 3
Output 2:
enter total element count in list:5
12
13
14
15
16
created list is [12, 13, 14, 15, 16]
enter element to search:17
Element not found

Binary Search Applications:


• In libraries of Java, .Net, C++ STL.
• While debugging, the binary search is used to pinpoint the place where the error
happens.
• Used to implement a dictionary.

Notes Prepared by: Mrs A Vineela, Assistant Professor, Dept of CSE, GMRIT
Differences between Linear and Binary Search:
Linear Search Binary Search

Starts searching from the first element Search the position of the searched
and compares each element with a element by finding the middle element
searched element of the array

Do not need the sorted list of element Need the sorted list of elements

Can be implemented on array and Cannot be directly implemented on


linked-list linked-list

Iterative in nature Divide and Conquer in nature

Easy to use Tricky to implement in comparison to


linear search

Fewer lines of code More lines of code

Preferred for a small size data set Preferred for a large size data set

Notes Prepared by: Mrs A Vineela, Assistant Professor, Dept of CSE, GMRIT
Lecture Notes-34 Python Programming

Sorting:
Sorting is defined as an arrangement of data in a certain order. Sorting techniques are used
to arrange data(mostly numerical) in an ascending or descending order. It is a method used
for the representation of data in a more comprehensible format.
Sorting a large amount of data can take a substantial amount of computing resources if the
methods we use to sort the data are inefficient.
The efficiency of the algorithm is proportional to the number of items it is traversing.
For a small amount of data, a complex sorting method may be more trouble than it is worth.
On the other hand, for larger amounts of data, we want to increase the efficiency and speed
as far as possible.
Some of the real-life examples of sorting are:
• Telephone Directory: It is a book that contains telephone numbers and addresses of
people in alphabetical order.
• Dictionary: It is a huge collection of words along with their meanings in alphabetical
order.
• Contact List: It is a list of contact numbers of people in alphabetical order on a mobile
phone.
A sorting algorithm is used to arrange elements of an array/list in a specific order. For example,

Here, we are sorting the array in ascending order.


There are various sorting algorithms that can be used to complete this operation. And, we can
use any algorithm based on the requirement.
The different sorting techniques are:
• Bubble Sort
• Selection Sort
• Insertion Sort
• Shell Sort
• Merge Sort

Notes Prepared by : Mrs A Vineela, Assistant Professor, Dept of CSE, GMRIT


Bubble Sort:

Bubble sort is a sorting algorithm that compares two adjacent elements and swaps them until
they are not in the intended order.
Just like the movement of air bubbles in the water that rise up to the surface, each element of
the array move to the end in each iteration. Therefore, it is called a bubble sort.
Working of Bubble Sort:
Suppose we are trying to sort the elements in ascending order.
1. First Iteration (Compare and Swap)
Starting from the first index, compare the first and the second elements. If the first element is
greater than the second element, they are swapped.
Now, compare the second and the third elements. Swap them if they are not in order.
The above process goes on until the last element.

2. Remaining Iteration:
The same process goes on for the remaining iterations. After each iteration, the largest element
among the unsorted elements is placed at the end.

Notes Prepared by : Mrs A Vineela, Assistant Professor, Dept of CSE, GMRIT


In each iteration, the comparison takes place up to the last unsorted element.

Notes Prepared by : Mrs A Vineela, Assistant Professor, Dept of CSE, GMRIT


Algorithm Bubble Sort:
bubbleSort(array)
for i <- 1 to indexOfLastUnsortedElement – 1
if leftElement > rightElement
swap leftElement and rightElement
end bubbleSort
Program:
# Bubble sort in Python
def bubbleSort(array):
for i in range(len(array)):
for j in range(0, len(array) - i - 1):
if array[j] > array[j + 1]:
temp = array[j]
array[j] = array[j+1]
array[j+1] = temp

#inserting elements in unsorted order


data = []
n=int(input('enter total number of elements:'))
print('enter each element')
for i in range(n):
data.append(int(input()))
print("list created :",data)

bubbleSort(data)
print('Sorted Array in Ascending Order:',data)

Output1:
enter total number of elements:8
enter each element
12
-2
15
-89
66
-8
456
12
list created : [12, -2, 15, -89, 66, -8, 456, 12]
Sorted Array in Ascending Order: [-89, -8, -2, 12, 12, 15, 66, 456]

Notes Prepared by : Mrs A Vineela, Assistant Professor, Dept of CSE, GMRIT


Output2:
enter total number of elements:5
enter each element
-2
45
0
11
-9
list created : [-2, 45, 0, 11, -9]
Sorted Array in Ascending Order: [-9, -2, 0, 11, 45]

Notes Prepared by : Mrs A Vineela, Assistant Professor, Dept of CSE, GMRIT


Lecture Notes-35 Python Programming

Classes and Objects in Python

Python is an “object-oriented programming language.” This means that almost all the code is
implemented using a special construct called classes. Programmers use classes to keep related
things together. This is done using the keyword “class,” which is a grouping of object-oriented
constructs.

Python Class

• In Python everything is an object. To create objects, the required Model or Plan or Blue
print, which is nothing but a class.
• Ability to write a class to represent properties (attributes) and actions (behavior) of
object.
• Properties can be represented by variables. Actions can be represented by Methods. Class
contains both variables and methods. A real-life example of class
Class: Person

State: Name, Sex, Profession

Behavior: Working, Study

Defining a Python Class:

All class definitions start with the class keyword, which is followed by the name of the class and
a colon. Any code that is indented below the class definition is considered part of the class’s
body.
Syntax:
class ClassName:
# Statement-1
.
.
# Statement-N

Notes Prepared By Mrs.L.Swathi, Assistant Professor, Dept of IT, GMRIT


The best practice is to use a docstring as the first statement in class to describe it.
class ClassName:
'''This is a class that I had created'''
print(ClassName.__doc__)
Output: This is a class that I had created

Create a Class:
class MyClass:
x=5
print(MyClass)
Output: <class '__main__.MyClass'>
Example:

class Dog:
pass
The body of the Dog class consists of a single statement: the pass keyword. Pass is often used as
a placeholder indicating where code will eventually go. It allows you to run this code without
Python throwing an error.

Example:

class member:

club= “XYZ club”

estab = 1992

We have created a class with name ‘member’ and we declared some variables here. Now to

access those variables inside ‘member’ we can use class name as follows:

class.club

class.estab

Output:

XYZ Club
1992

Notes Prepared By Mrs.L.Swathi, Assistant Professor, Dept of IT, GMRIT


Examaple:
class Dog:
def __init__(self, name, age):

self.name = name

self.age = age

The properties that all Dog objects must have are defined in a method called .__init__(). Every
time a new Dog object is created, .__init__() sets the initial state of the object by assigning the
values of the object’s properties. You can give .__init__() any number of parameters, but the first
parameter will always be a variable called self. When a new class instance is created, the
instance is automatically passed to the self parameter in .__init__() so that new attributes can be
defined on the object. The .__init__() method’s signature is indented four spaces. The body of
the method is indented by eight spaces. This indentation is important. It tells Python that
the .__init__() method belongs to the Dog class.

In the body of .__init__(), there are two statements using the self variable:

1. self.name = name creates an attribute called name and assigns to it the value of
the name parameter.
2. self. age = age creates an attribute called age and assigns to it the value of
the age parameter.

Attributes created in .__init__() are called instance attributes. An instance attribute’s value is
specific to a particular instance of the class.
On the other hand, class attributes are attributes that have the same value for all class instances.
You can define a class attribute by assigning a value to a variable name outside of .__init__().

For example, the following Dog class has a class attribute called species with the
value "Canis familiaris":

class Dog:
# Class attribute
species = "Canis familiaris"

def __init__(self, name, age):

Notes Prepared By Mrs.L.Swathi, Assistant Professor, Dept of IT, GMRIT


self.name = name
self.age = age

Example-2:

class Product:
def __init__(self, name, cost, price):
self.name = name
self.cost = cost
self.price = price
def profit_margin(self):
return self.price - self.cost

Objects:

Objects are an instance of a class. It is an entity that has state and behavior. In a nutshell, it is an
instance of a class that can access the data.

Python is an object-oriented programming language. Everything is in Python treated as an object,


including variable, function, list, tuple, dictionary, set, etc. Every object belongs to its class.

For example - An integer variable belongs to integer class. An object is a real-life entity. An
object is the collection of various data and functions that operate on those data.
An object contains the following properties.

State - Attributes or Properties of an object.


Behavior - The method of an object represents its behavior.
Identity - Each object must be uniquely identified and allow interacting with the other objects.

Notes Prepared By Mrs.L.Swathi, Assistant Professor, Dept of IT, GMRIT


Here, we have the blueprint of a car on the left side. This is known as the class while on the right
side we have some of the models of the cars based on that blueprint, which are known as
the objects (instances of the class) of the particular class.

Syntax: obj = class1()

Creating an Object and Class in python:


class employee():
def __init__(self,name,age,id,salary):
self.name = name
self.age = age
self.salary = salary
self.id = id
emp1 = employee("harshit",22,1000,1234)
emp2 = employee("arjun",23,2000,2234)
print(emp1.__dict__)

Output:{'name': 'harshit', 'age': 22, 'salary': 1234, 'id': 1000}

***

Notes Prepared By Mrs.L.Swathi, Assistant Professor, Dept of IT, GMRIT


Lecture Notes-36 Python Programming

Object-Creating an Object in Python, the Constructor Method


An object is a real-life entity. An object is the collection of various data and functions that
operate on those data.

Creating an Object of a Class in Python


The object is created after creating a class. Instant of the object is created using the name same as
the class name and it is known as Object Instantiation. One can give any name to a newly created
object. Object creation is similar to calling a function.
#object instantiation
object_name = class_name()

Create Object
class MyClass:
x=5
p1 = MyClass()
print(p1.x)
Output: 5

Example2:
class Cars:
def __init__(self, m, p):
self.model = m
self.price = p
Audi = Cars("R8", 100000)
print(Audi.model)
print(Audi.price)
Output: R8
100000
Audi = Cars():

Notes Prepared By Mrs.L.Swathi, Assistant Professor, Dept of IT, GMRIT


• A block of memory is allocated on the heap. The size of memory allocated is decided by
the attributes and methods available in that class(Cars).
• After the memory block is allocated, the special method __init__() is called internally.
Initial data is stored into the variables through this method.
• The location of the allocated memory address of the instance is returned to the
object(Cars).
• The memory location is passed to self.

Example3:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p1 = Person("John", 36)
print(p1.name)
print(p1.age)
Output: John
36

Accessing Objects:

(i)Accessing object variables in Python


# Creating a class named Display
class Display:
a = 10
b = 25
c = 50
# Creating an object named "obj1", "obj2" & accessing the class properties (attributes).
obj1 = Display()
print(obj1.a)
print(obj1.b)

Notes Prepared By Mrs.L.Swathi, Assistant Professor, Dept of IT, GMRIT


obj2 = Display()
print(obj2.c)

Output: 10
25
50

(ii)Accessing object functions in Python:


As we know inside classes we can declare functions, which are known as methods. Objects can
also contain such methods (functions), and pass the arguments to through those methods.
Methods of an object are the corresponding function of that particular class.

class Person:
def __init__(self, name,hobby):
self.name = name
self.hobby= hobby
def new(self):
print("Heyy my name is " + self.name + ". I Love " + self.hobby)
obj2 = Person("abc","coding")
obj2.new()
Output: Heyy my name is abc. I Love coding

(iii) Modify object properties in Python


Once we declare objects, we can later modify their properties and values.
class Python:
a = 10
# Declaring an object
obj1 = Python()
print(obj1.a)
#Modifying value
obj1.a = 200
print("After modifying the object properties")

Notes Prepared By Mrs.L.Swathi, Assistant Professor, Dept of IT, GMRIT


print(obj1.a)
Output: 10
10
After modifying the object properties
200

(iv) Delete object properties in Python


We can even delete the properties (also known as attributes) of an object with the help of the
del keyword.
del obj1.a
v) Delete an object in Python
You have created an object earlier and now want to delete it? We also have a way to delete an
object which was created earlier in the code by using the del keyword.
del obj1.
Constructor
✓ It is a special method in python
✓ The name of the constructor should be _init_ (self)
✓ In Python, the method the __init__() simulates the constructor of the class. This method
is called when the class is instantiated. It accepts the self-keyword as a first argument
which allows accessing the attributes or method of the class.
✓ Constructor will be executed automatically at the time of object creation.
✓ The main purpose of constructor is to declare and initialize instance variables.
✓ Per object constructor will be executed only once.
✓ Constructor can take at least one argument(at least self)
✓ Constructor is optional and if we are not providing any constructor then python will
provide default constructor.

Types of constructors

There are two types of constructors:

1. Default constructor
Notes Prepared By Mrs.L.Swathi, Assistant Professor, Dept of IT, GMRIT
2. Parameterized constructor
3. Non-Parameterized constructor

The default constructor is a constructor that takes no arguments. It contains only one argument
called self, which is a reference to the instance that is being built.

Example1:
class Employee:
def display(self):
print('Inside Display')
emp = Employee()
emp.display()
Output: Inside Display

Example2:
class Assignments:
check= "not done"
def is_done(self):
print(self.check)
obj = Assignments()
obj.is_done()
Output: not done
Parameterized constructors are constructors that have parameters and a reference to the
instance being created called self. The self reference serves as the first argument.
Example1:
class Triangle:
base = 0
height = 0
area = 0
def __init__(self, b, h):
self.base = b
self.height = h
Notes Prepared By Mrs.L.Swathi, Assistant Professor, Dept of IT, GMRIT
def areaOfTriangle(self):
self.area = self.base * self.height * 0.5
print("Area of triangle: " + str(self.area))
obj = Triangle(5, 14)
obj.areaOfTriangle()
Output: Area of triangle: 35.0

Example2:
class Family:
# Constructor - parameterized
members=5
def __init__(self, count):
print("This is parameterized constructor")
self.members = count
def show(self):
print("No. of members are ",self.members)
object = Family(10)
object.show()
Output: This is parameterized constructor
No. of members are 10

• An object of the class Family is created. It has a variable known as members.


• When the object is created, a parameter (here it is 10) is passed as arguments.
• This parameter (10) is taken up by the constructor as the object is created.
• The number 10 is assigned to the variable count which is further assigned
to self.members.
• The self.members can be used within the class to print the data.

Notes Prepared By Mrs.L.Swathi, Assistant Professor, Dept of IT, GMRIT


Example3:
class Employee:
def __init__(self, name, id):
self.id = id
self.name = name
def display(self):
print("ID: %d \nName: %s" % (self.id, self.name))
emp1 = Employee("John", 101)
emp2 = Employee("David", 102)
emp1.display()
emp2.display()
Output: ID:101
Name:John
ID:102
Name:David.

A constructor without any arguments is called a non-parameterized constructor. This type of


constructor is used to initialize each object with default values.
class Company:
# no-argument constructor
def __init__(self):
self.name = "Python"
self.address = "ABC Street"
# a method for printing data members
def show(self):
print('Name:', self.name, 'Address:', self.address)
# creating object of the class
cmp = Company()
# calling the instance method using the object
cmp.show()
Notes Prepared By Mrs.L.Swathi, Assistant Professor, Dept of IT, GMRIT
Output: Name: Python Address: ABC Street

***

Notes Prepared By Mrs.L.Swathi, Assistant Professor, Dept of IT, GMRIT


Lecture Notes-37 Python Programming

Classes with Multiple Objects, File Object


Create a list of object in Python class

We can create list of object in Python by appending class instances to list. By this, every index in the
list can point to instance attributes and methods of the class and can access them. If you observe it
closely, a list of objects behaves like an array of structures in C.
Example1:
class Person:
def __init__(self, name, roll):
self.name = name
self.roll = roll
# creating list
list = []
# appending instances to list
list.append( Person('Akash', 2) )
list.append( Person('Dinesh', 40) )
list.append( Person('Deepa', 44) )
for obj in list:
print( obj.name, obj.roll, sep =' ' )
Output: Akash 2
Dinesh 40
Deepa 44

Example2:
class Addition:
def __init__(self, x, y):
self.x = x
self.y = y
def Sum(self):
print( self.x + self.y )
# creating list
list = []

Notes Prepared By Mrs.L.Swathi, Assistant Professor, Dept of IT, GMRIT


# appending instances to list
list.append(Addition (2, 3) )
list.append(Addition (12, 13) )
list.append(Addition (22, 33) )
for obj in list:
# calling method
obj.Sum()
Output:5
25
55
File Object
Python file object provides methods and attributes to access and manipulate files. Using file
objects, we can read or write any files.
Whenever we open a file to perform any operations on it, Python returns a file object. To create a
file object in Python use the built-in functions, such as open () and os.open().
IOError exception is raised when a file object is misused, or file operation fails for an I/O-related
reason. For example, when you try to write to a file when a file is opened in read-only mode.
Types of File Object
In Python, there are three different categories of a file object, which are listed below:
1) Text files
2) Binary files
3) Raw files
All file types objects are defined in the io module.

Text files (TextIOWrapper)


The text file type is most common. Usually, we use text files to store character data or storing
information in plain text with no special formatting beyond basic fonts and font styles.
We open a text file using the open() function.
For example, open(“test.txt”, “r”).
When we open a text file, it returns a TextIOWrapper file object.
file = open(“test.txt”, “w”)

Notes Prepared By Mrs.L.Swathi, Assistant Professor, Dept of IT, GMRIT


print(type(file))
# Output: <class '_io.TextIOWrapper'>
Binary Files (BufferedReader and BufferedWriter)
• Data is stored on a disk in the form of binary. For example, we use binary files to store
data like images or videos. Binary files are a computer-readable form of storing data.
• A program is needed to interpret the data in a binary file and display it to the user. The
binary files are also called buffered files. This file type is used for reading and writing
binary data.
• Open the binary files using the open() function in binary mode.
For example, open(“abc.txt”, “rb”). It opens the file to read-only in binary mode. The file pointer
exists at the beginning of the file.
The open() function will return the BufferedReader when we open the binary file for reading and
the BufferedWriter file object when we open a binary file for writing.
file = open(“test.txt”, “rb”)
print(type(file))
# Output: <class '_io.BufferedReader'>
Raw Files
• A raw file is a collection of unprocessed data. It means the raw file has not been altered
or manipulated in any way by the computer.
• The raw files are also called unbuffered files, and this file type is generally used as a low-
level building block for binary and text streams. Mostly, the raw file is not used.
• When we open these files, using the open() function will return a FileIO object.
file = open(“test.txt”, “rb”, buffering=0)
print(type(file))
# Output: <class '_io.FileIO'>

File Object Attributes


File object has the following attributes that we can use to accessing various details of a file, such
as a file name and under which mode the file is opened.
• name: Return the name of the file.

Notes Prepared By Mrs.L.Swathi, Assistant Professor, Dept of IT, GMRIT


• encoding: It returns the encoding this file uses, such as UTF-8. This attribute is read-only.
When Unicode strings are written to a file, they will be converted to byte strings using this
encoding. It may also be None. In that case, the file uses the system default encoding for
converting Unicode strings.
• mode: Returns the file access mode used while opening a file.
• closed: Returns True if a file is closed. It is a Boolean value indicating the current state of
the file object.
• newline: Files opened in universal newline read mode keep track of the newlines
encountered while reading the file. The values are ‘\r’, ‘\n’, ‘\r\n’, None (no newlines read
yet), or a tuple containing all the newline types seen.
• readable()-Retruns boolean value indicates that whether file is readable or not
• writable()-Returns boolean value indicates that whether file is writable or not

Example:
f=open("abc.txt",'w')
print("File Name: ",f.name)
print("File Mode: ",f.mode)
print("Is File Readable: ",f.readable())
print("Is File Writable: ",f.writable())
print("Is File Closed : ",f.closed)
f.close()
print("Is File Closed : ",f.closed)
Output:
File Name: abc.txt
File Mode: w
IsFile Readable: False
Is File Writable: True
Is File Closed : False
Is File Closed : True

Notes Prepared By Mrs.L.Swathi, Assistant Professor, Dept of IT, GMRIT


File Object Methods
File object has the following methods that we can use to accessing a file: A file can be opened
with a built-in function called open(). This function takes in the file’s path and the access mode
and returns a file object.
read():-It reads the entire file and returns it contents in the form of a string. If the size
argument is negative or omitted, read all data until EOF is reached.
# Reading a file
f = open(__file__, 'r')
#read()
text = f.read(10)
print(text)
f.close()
readline():- Read single line
# Reading a line in a file
f = open(__file__, 'r')
#readline()
text = f.readline(20)
print(text)
f.close()

readlines():- It reads the entire file line by line and updates each line to a list
#Reading a file
f = open(__file__, 'r')
#readline()
text = f.readlines(25)
print(text)
f.close()

write(string):- It writes the contents of string to the file. It has no return value.
# Writing a file

Notes Prepared By Mrs.L.Swathi, Assistant Professor, Dept of IT, GMRIT


f = open(__file__, 'w')
line = 'Welcome to Python Class\n'
#write()
f.write(line)
f.close()

writelines():- Writes a list of strings to the file.


# Writing a file
f = open(__file__, 'a+')
lines = f.readlines()
#writelines()
f.writelines(lines)
f.close()

tell():- It returns an integer that tells us the file object’s position from the beginning of the file in
the form of bytes
# Telling the file object position
f = open(__file__, 'r')
lines = f.read(10)
#tell()
print(f.tell())
f.close()
seek(offset, from_where):- Set file pointer position in a file. Offset indicates the number of
bytes to be moved. from_where indicates from where the bytes are to be moved.
# Setting the file object position
f = open(__file__, 'r')
lines = f.read(10)
print(lines)
#seek()
print(f.seek(2,2))
lines = f.read(10)

Notes Prepared By Mrs.L.Swathi, Assistant Professor, Dept of IT, GMRIT


print(lines)
f.close()
flush():- Flush the internal buffer, like stdio‘s fflush(). It has no return value. close()
automatically flushes the data but if you want to flush the data before closing the file then you
can use this method.

# Clearing the internal buffer before closing the file


f = open(__file__, 'r')
lines = f.read(10)
#flush()
f.flush()
print(f.read())
f.close()
isatty(): Returns True if the file is connected to a tty(-like) device and False if not.
# Checks if file is connected to a tty(-like) device
f = open(__file__, 'r')
#isatty()
print(f.isatty())
f.close()

truncate():- Truncate the file’s size. The size defaults to the current position. The current file
position is not changed.
# Truncates the file
f = open(__file__, 'w')
#truncate()
f.truncate(10)
f.close()

close():- Used to close an open file. A closed file cannot be read or written any more.
# Opening and closing a file
f = open(__file__, 'r')

Notes Prepared By Mrs.L.Swathi, Assistant Professor, Dept of IT, GMRIT


#close()
f.close()

***

Notes Prepared By Mrs.L.Swathi, Assistant Professor, Dept of IT, GMRIT


Lecture Notes-38 Python Programming
Exception Handling
Exception handling for the Following Reasons:
Error Handling: In the case of Errors during runtime, the application might terminate
unconditionally. Using the Exception Handling, we can handle the scenario of Failures and
avoid termination of the program.

Code Separation: Error Handling can help us segregate the code that is required for error
handling from the main logic. The error related code can be placed inside the “except” block
which is segregating it from the regular code that contains the application logic.

Grouping Error Type and Error Differentiation: It can help us to segregate different kinds
of errors that are encountered during the execution. We can have multiple “except” blocks, each
handling a specific kind of error. In the article below, we will see the implementation of multiple
“except” blocks to handle different types of error.

In any programming language there are 2 types of errors are possible.


1. Syntax Errors
2. Runtime Errors
1. Syntax Errors: The errors which occurs because of invalid syntax are called syntax errors.
>>> x=10 if x==10 print("Hello")
SyntaxError: invalid syntax
>>>print "Hello"
SyntaxError: Missing parentheses in call to 'print'
Note: Programmer is responsible to correct these syntax errors. Once all syntax errors are
corrected then only program execution will be started.

2. Runtime Errors: Also known as exceptions. While executing the program if something
goes wrong because of end user input or programming logic or memory problems etc then we
will get Runtime Errors.

>>> print(10/0)
ZeroDivisionError: division by zero
print(10/"ten")
TypeError: unsupported operand type(s) for /: 'int' and 'str'

Notes Prepared by : S Vinodkumar, Assistant Professor, Dept of CSE, GMRIT


>>> x=int(input("Enter Number:"))
print(x)
Enter Number:ten ValueError: invalid literal for int() with base 10: 'ten'

Note: Exception Handling concept applicable for Runtime Errors but not for syntax errors
Exception:
An Exception is an event , which occurs during the execution of a program, that disrupts the
normal flow of the program’s instructions.
Exception Handling:
Process of responding to the occurrence, during computation, of an exceptional conditions
required special processing-often changing the normal flow of the program execution.
• Whenever a runtime error occurs, it creates an exception.
• Usually, the program stops and Python prints an error message.
Examples:
For example, dividing by zero creates an exception:
>>> print 55/0
ZeroDivisionError: integer division or modulo
So does accessing a nonexistent list item:
>>> a = []
>>> print a[5]
IndexError: list index out of range
Or accessing a key that isn’t in the dictionary:
>>> b = {}
>>> print b[’what’]
KeyError: what
Try and except block : Handling Exceptions
Sometimes we want to execute an operation that could cause an exception, but we don’t want
the program to stop. We can handle the exception using the try and except statements.

The try and except statement works as follows.

• First, the try clause (the statement(s) between the try and except keywords) is
executed.
Notes Prepared by : S Vinodkumar, Assistant Professor, Dept of CSE, GMRIT
• If no exception occurs, the except clause is skipped and execution of the try statement
is finished.
• If an exception occurs during execution of the try clause, the rest of the clause is
skipped. Then, if its type matches the exception named after the except keyword,
the except clause is executed, and then execution continues after the try/except block.
• If an exception occurs which does not match the exception named in the except clause,
it is passed on to outer try statements; if no handler is found, it is an unhandled
exception and execution stops with a message as shown above.
Process of Exception Handling:
try:
# Run this code
except:
#Excecute this code when there is an exception
else:
#No exceptions? Run this code

finally:
#Always run this code

Example1 :
try:
print(4/0)
except ZeroDivisionError:
print("Division by zero is undefined")

Output:
Division by zero is undefined

Example 2:
try:
print(12+"string")
except TypeError as e:
print(e)

Output:
unsupported operand type(s) for +: ‘int’ and ‘str’
Notes Prepared by : S Vinodkumar, Assistant Professor, Dept of CSE, GMRIT
Example 3:
try:
print(4/0)
print(12+"string")
except (TypeError, ZeroDivisionError):
print("This an error.")
Output:
This an error.

***

Notes Prepared by : S Vinodkumar, Assistant Professor, Dept of CSE, GMRIT


Lecture Notes-39 Python Programming
Raising An Exception:
Raise to throw an exception if a condition occurs.
Example:
x = 10
if x > 5:
raise Exception('x should not exceed 5.The value of x was: {}'.format(x))
Output:
Traceback (most recent call last):
File "<pyshell#14>", line 2, in <module>
raise Exception('x should not exceed 5.The value of x was: {}'.format(x))
Exception: x should not exceed 5.The value of x was: 10
Finally:
When we need to make sure something will be done no matter meets exceptions or not, this
feature is very useful. For instance, when we open a file and do some operations on it, we
should make sure we will close the file finally.
Example:
try:
print(4/0)
except ZeroDivisionError as e:
print(e)
finally:
print("I will always execute")

Output :
division by zero
I will always execute
***

Notes Prepared by : S Vinodkumar, Assistant Professor, Dept of CSE, GMRIT


Lecture Notes-40 Python Programming
User Defined Exception :
• Python allows us to define our own custom exceptions. Exceptions should typically be
derived from the Exception class, either directly or indirectly.
• Exception classes can be defined which do anything any other class can do, but are
usually kept simple, often only offering a number of attributes that allow information
about the error to be extracted by handlers for the exception.
• Most exceptions are defined with names that end in “Error”, similar to the naming of
the standard exceptions.
• Many standard modules define their own exceptions to report errors that may occur in
functions they define.

Example:
try:
x = 'something'
if x == 'something':
raise Exception
except Exception:
print("x is something")
Output:
x is something

Refer the Example in Notes 38 and 39.

***

Notes Prepared by : S Vinodkumar, Assistant Professor, Dept of CSE, GMRIT


Lecture Notes 41 Python Programming
Introduction to Numpy and Pandas:
Pandas:
• Pandas is a very popular library for working with data (its goal is to be the most powerful
and flexible open-source tool, and in our opinion, it has reached that goal). Pandas is a
Python library used for working with data sets. It has functions for analyzing, cleaning,
exploring, and manipulating data.
• The name "Pandas" has a reference to both "Panel Data", and "Python Data Analysis"
and was created by Wes McKinney in 2008.
• Pandas has helpful functions for handling missing data, performing operations on
columns and rows, and transforming data. If that wasn’t enough, a lot of SQL functions
have counterparts in pandas, such as join, merge, filter by, and group by. With all of these
powerful tools, it should come as no surprise that pandas are very popular among data
scientists.
Numpy:
• Numpy is an open-source Python library that facilitates efficient numerical operations on
large quantities of data. The most important part about Numpy is that Pandas is built on
top of it. So, Numpy is a dependency of Pandas.
• Numpy is a Python library used for working with arrays. It also has functions for working
in domain of linear algebra, fourier transform, and matrices. Numpy stands for Numerical
Python.
• Numpy was created in 2005 by Travis Oliphant. It is an open source project and you can
use it freely.
Installation:
If Anaconda is already installed, Numpy and Pandas may have been auto-installed. If they
haven’t been, or if we want to update to the latest versions, we can open a terminal window and
run the following commands:
conda install numpy
conda install pandas

Notes Prepared by: Mrs. P. Someswari, Assistant Professor, Dept of CSE, GMRIT
If we don’t have Anaconda installed, we can alternatively install the libraries using pip by
running the following commands from terminal:
pip install numpy
pip install pandas
Once we have installed these libraries, we are ready to open any Python coding environment (we
recommend Jupyter Notebook). In order to use these libraries, we need to import them using the
following lines of code. We’ll use the abbreviations np and pd, respectively to simplify our
function calls in the future.
import numpy as np
import pandas as pd
Arrays:
An array is a data type used to store multiple values using a single identifier (variable name). An
array contains an ordered collection of data elements where each element is of the same type and
can be referenced by its index (position).
The important characteristics of an array are:
• Each element of the array is of same data type, though the values stored in them may be
different.
• The entire array is stored contiguously in memory. This makes operations on array fast.
• Each element of the array is identified or referred using the name of the Array along with
the index of that element, which is unique for each element.
• The index of an element is an integral value associated with the element, based on the
element’s position in the array.
Difference between List and Array:
ist Array
List can have elements of different data types. All elements of an array are of same data type.
for example , [1,2.0,-3,’hello’,’a@’] for example, an array of floats may be:
[1.2, 5.4, 2.7]
Elements in list are not stored continuously in Array elements are stored in contiguous
memory. memory locations. This makes operations on
arrays faster than lists.

Notes Prepared by: Mrs. P. Someswari, Assistant Professor, Dept of CSE, GMRIT
Lists do not support element wise operations, Arrays support element wise operations. For
for example, addition, multiplication, etc. example, if A1 is an array, it is possible to say
because elements may not be of same type. A1/3 to divide each element of the array by 3.
Lists can contain objects of different datatype Numpy array takes up less space in memory as
that Python must store the type information for compared to a list because arrays do not
every element along with its element value. require storing the data type of each element
Thus lists take more space in memory and are separately.
less efficient.
List is a part of core Python. Array (ndarray) is a part of NumPy library.

Numpy Arrays:
• NumPy arrays are used to store lists of numerical data, vectors and matrices.
• The NumPy library has a large set of routines (built-in functions) for creating,
manipulating, and transforming NumPy arrays.
• Python language also has an array data structure, but it is not as versatile, efficient and
useful as the NumPy array.
• The NumPy array has contiguous memory allocation i.e., the memory space must be
divided into the fixed sized position and each position is allocated to a single data only.
Creation of NumPy Arrays from List:
There are several ways to create arrays. To create an array and to use its methods, first we need
to import the NumPy library.
#NumPy is loaded as np (we can assign any #name), numpy must be written in lowercase
>>> import numpy as np
The NumPy’s array() function converts a given list into an array.
Example:
#Create an array called array1 from the given list.
array1 = np.array([10,20,30]) #Display the contents of the array
array1 #array([10, 20, 30])
print(array1) # [10 20 30]

Notes Prepared by: Mrs. P. Someswari, Assistant Professor, Dept of CSE, GMRIT
#incorrect way of declaring array
a = np.array(1,2,3,4)
#correct way of declaring array
a = np.array([1,2,3,4])
Creating a 1-D array:
An array with a single row of elements is called 1-D array. It may contain numbers or strings and
so on.
Example:
array2=np.array([5,-7.4,’a’,7.2])
array2
Output:
array(['5', '-7.4', 'a', '7.2'], dtype='<U32')
Since, there is a string value in the list, all the integer and float values have been promoted to
string, while converting the list to array.
Creating a 2-D array:
A 2-D array can be created by passing nested lists to the array() function.
Example:
array3=np.array([[2.4,3],[4.91,7],[0,-1]])
array3
Output:
array([[ 2.4 , 3. ],
[ 4.91, 7. ],
[ 0. , -1. ]])
Other Ways of creating numpy arrays:
1. We can specify data type (integer, float, etc.) while creating array using dtype as an
argument to array(). This will convert the data automatically to the mentioned type.
Example 1:
import numpy as np
array4 = np.array( [ [1,2], [3,4] ], dtype=float)
array4

Notes Prepared by: Mrs. P. Someswari, Assistant Professor, Dept of CSE, GMRIT
Output:
array([[1., 2.],
[3., 4.]])
Example 2:
import numpy as np
array5 = np.array( [ [1.4567,2.45], [3.09,4.45] ], dtype=int)
array5
Output:
array([[1, 2],
[3, 4]])
2. We can create an array with all elements initialized to 0 using the function zeros(). By
default, the data type of the array created by zeros() is float. The following code will
create an array with 3 rows and 4 columns with each element set to 0:
Example1:
array6 = np.zeros((3,4))
array6
Output:
array([[0., 0., 0., 0.],
[0., 0., 0., 0.],
[0., 0., 0., 0.]])
3. We can create an array with all elements initialized to 1 using the function ones(). By
default, the data type of the array created by ones() is float. The following code will
create an array with 3 rows and 2 columns:
Example:
array7 = np.ones((3,2))
array7
Output:
array([[1., 1.],
[1., 1.],
[1., 1.]])

Notes Prepared by: Mrs. P. Someswari, Assistant Professor, Dept of CSE, GMRIT
4. We can create an array with numbers in a given range and sequence using the arange()
function. This function is analogous to the range() function of Python.
Example 1:
array8 = np.arange(6) # an array of 6 elements is created with start value 0 and step size 1
array8
Output:
array([0, 1, 2, 3, 4, 5])
Example 2:
# Creating an array with start value -2, end value 24 and step size 4
array9 = np.arange( -2, 24, 4 )
array9
Output:
array([-2, 2, 6, 10, 14, 18, 22])
Accessing Elements from Numpy Array:
NumPy arrays can be indexed, sliced and iterated over.
a. Indexing:
For 2-D arrays, indexing for both dimensions starts from 0, and each element is referenced
through two indexes i and j, where i represents the row number and j represents the column
number.

Table: marks of students in different subjects


Consider the table above that shows marks obtained by students in three different subjects. Let us
create an array called marks to store marks given in three subjects for four students given in this
table. As there are 4 students (i.e. 4 rows) and 3 subjects (i.e. 3 columns), the array will be called
marks[4][3]. This array can store 4*3 = 12 elements.

Notes Prepared by: Mrs. P. Someswari, Assistant Professor, Dept of CSE, GMRIT
Here, marks[i,j] refers to the element at (i+1)th row and (j+1)th column because the index value
starts at 0. Thus marks[3,1] is the element in 4th row and 2nd column which is 72 (marks of
Prasad in English).
Example:
import numpy as np
marks=np.array([[78,67,56],[76,75,47],[84,59,60],[67,72,54]])
marks
output:
array([[78, 67, 56],
[76, 75, 47],
[84, 59, 60],
[67, 72, 54]])
# accesses the element in the 1st row in the 3rd column
marks[0,2]
#56
marks [0,4]
#index Out of Bound "Index Error".
Index 4 is out of bounds for axis with size 3
b. Slicing:
Sometimes it is necessary to extract a part of an array. This is done through slicing. We can
define which part of the array to be sliced by specifying the start and end index values using
[start:end] along with the array name.
Example 1:
#creating ARRAY
import numpy as np
array8=np.array([-2, 2, 6, 10, 14, 18, 22])
array8
# excludes the value at the end index
array8[3:5]
# reverse the array
array8[ : : -1]
Notes Prepared by: Mrs. P. Someswari, Assistant Professor, Dept of CSE, GMRIT
Output:
array([-2, 2, 6, 10, 14, 18, 22])
array([10,14])
array([22,18,14,10,6,2,-2])
Example 2:
Slicing is done for 2-D arrays. For this, let us create a 2-D array called array9 having 3 rows and
4 columns.
Example:
array9 = np.array([[ -7, 0, 10, 20], [ -5, 1, 40, 200], [ -1, 1, 4, 30]])
# access all the elements in the 3rd column
array9[0:3,2] # specified rows in the range 0:3 because the end value of the range is excluded.
Output:
array([10, 40, 4])
print(array9[0:2,2] ) # array([10, 40]) since specified rows in the range 0:2.
# access elements of 2nd and 3rd row from 1st # and 2nd column
array9[1:3,0:2]
array([[-5, 1], [-1, 1]])
If row indices are not specified, it means all the rows are to be considered. Likewise, if column
indices are not specified, all the columns are to be considered. Thus, the statement to access all
the elements in the 3rd column can also be written as:
array9[:,2]
Output:
array([10, 40, 4])

Notes Prepared by: Mrs. P. Someswari, Assistant Professor, Dept of CSE, GMRIT
Lecture Notes 42 Python Programming

Basic Operations on Numpy Arrays


Once arrays are declared, we can access it's elements or perform certain operations.
1. Arithmetic Operations:
These operations on NumPy arrays are fast and simple. When we perform a basic arithmetic
operation like addition, subtraction, multiplication, division etc. on two arrays, the operation is
done on each corresponding pair of elements. For instance, adding two arrays will result in the
first element in the first array to be added to the first element in the second array, and so on.
Consider the following element-wise operations on two arrays:
import numpy as np
array1 = np.array([[3,6],[4,2]])
array2 = np.array([[10,20],[15,12]])
#Element-wise addition of two matrices.
array1 + array2
Output:
array([[13, 26],
[19, 14]])
#Subtraction
array1 - array2
Output:
array([[ -7, -14],
[-11, -10]])
#Multiplication
array1 * array2
array([[ 30, 120],
[ 60, 24]])
#Matrix Multiplication
array1 @ array2
Output:
array([[120, 132],

Notes Prepared by: Mrs. P. Someswari, Assistant Professor, Dept of CSE, GMRIT
[ 70, 104]])
#Exponentiation
array1 ** 3
Output:
array([[ 27, 216],
[ 64, 8]], dtype=int32)
#Division >>> array2 / array1
Output:
array([[3.33333333, 3.33333333],
[3.75 , 6. ]])
#Element wise Remainder of Division #(Modulo)
array2 % array1
Output:
array([[1, 2],
[3, 0]], dtype=int32)
It is important to note that for element-wise operations, size of both arrays must be same. That is,
array1.shape must be equal to array2.shape.

2. Transpose:
Transposing an array turns its rows into columns and columns to rows just like matrices in
mathematics.
#Transpose
import numpy as np
array3 = np.array([[10,-7,0, 20], [-5,1,200,40],[30,1,-1,4]])
array3
Output:
array([[ 10, -7, 0, 20],
[ -5, 1, 200, 40],
[ 30, 1, -1, 4]]) # the original array does not change
array3.transpose() # it transposes the original array
Output:

Notes Prepared by: Mrs. P. Someswari, Assistant Professor, Dept of CSE, GMRIT
array([[ 10, -5, 30],
[ -7, 1, 1],
[ 0, 200, -1],
[ 20, 40, 4]])

3. Sorting:
Sorting is to arrange the elements of an array in an order either ascending or descending. By
default, numpy does sorting in ascending order.
import numpy as np
array4 = np.array([1,0,2,-3,6,8,4,7])
array4.sort()
array4
Output:
array([-3, 0, 1, 2, 4, 6, 7, 8])
array3 = np.array([[10,-7,0, 20], [-5,1,200,40],[30,1,-1,4]])
array3.sort()
array3
Output:
array([[ -7, 0, 10, 20],
[ -5, 1, 40, 200],
[ -1, 1, 4, 30]])
array5 = np.array([[10,-7,0, 20], [-5,1,200,40],[30,1,-1,4]])
#axis =0 means column-wise sorting
array5.sort(axis=0)
array5
Output:
array([[ -5, -7, -1, 4],
[ 10, 1, 0, 20],
[ 30, 1, 200, 40]])
***

Notes Prepared by: Mrs. P. Someswari, Assistant Professor, Dept of CSE, GMRIT
Lecture Notes-43 Python Programming
Introduction to Pandas
Pandas is an open-source library that is made mainly for working with relational or labeled
data both easily and intuitively. It provides various data structures and operations for
manipulating numerical data and time series. This library is built on top of the NumPy
library. Pandas is fast and it has high performance & productivity for users.
History: Pandas were initially developed by Wes McKinney in 2008 while he was working
at AQR Capital Management. He convinced the AQR to allow him to open source the
Pandas. Another AQR employee, Chang She, joined as the second major contributor to the
library in 2012. Over time many versions of pandas have been released. The latest version
of the pandas is 1.4.1
Advantages
• Fast and efficient for manipulating and analyzing data.
• Data from different file objects can be loaded.
• Easy handling of missing data (represented as NaN) in floating point as well as non-
floating point data
• Size mutability: columns can be inserted and deleted from DataFrame and higher
dimensional objects
• Data set merging and joining.
• Flexible reshaping and pivoting of data sets
• Provides time-series functionality.
• Powerful group by functionality for performing split-apply-combine operations on
data sets.

Getting Started

The first step of working in pandas is to ensure whether it is installed in the Python folder
or not. If not then we need to install it in our system using pip command. Type cmd
command in the search box and locate the folder using cd command where python-pip
file has been installed. After locating it, type the command:
pip install pandas
After the pandas have been installed into the system, you need to import the library. This
module is generally imported as:
import pandas as pd
Here, pd is referred to as an alias to the Pandas.

Pandas generally provide two data structures for manipulating data, They are:
• Series
• DataFrame
Series: Pandas Series is a one-dimensional labeled array capable of holding data of any
type (integer, string, float, python objects, etc.). The axis labels are collectively called

Notes Prepared by : Mr D Siva Krishna, Assistant Professor, Dept of CSE, GMRIT


Lecture Notes-43 Python Programming
indexes. Pandas Series is nothing but a column in an excel sheet. Labels need not be unique
but must be a hashable type. The object supports both integer and label-based indexing and
provides a host of methods for performing operations involving the index.


Creating a Series
In the real world, a Pandas Series will be created by loading the datasets from existing
storage, storage can be SQL Database, CSV file, an Excel file. Pandas Series can be created
from the lists, dictionary, and from a scalar value etc.
import pandas as pd
import numpy as np
# Creating empty series
ser = pd.Series()
print(ser)
# simple array
data = np.array(['g', 'm', 'r', 'i', 't'])
ser = pd.Series(data)
print(ser)

Output:
Series([], dtype: float64)
0 g
1 m
2 r
3 i
4 t
dtype: object

DataFrame

Pandas DataFrame is a two-dimensional size-mutable, potentially heterogeneous tabular


data structure with labeled axes (rows and columns). A Data frame is a two-dimensional
data structure, i.e., data is aligned in a tabular fashion in rows and columns. Pandas
DataFrame consists of three principal components, the data, rows, and columns.

Notes Prepared by : Mr D Siva Krishna, Assistant Professor, Dept of CSE, GMRIT


Lecture Notes-43 Python Programming

Creating a DataFrame:
In the real world, a Pandas DataFrame will be created by loading the datasets from existing
storage, storage can be SQL Database, CSV file, an Excel file. Pandas DataFrame can be
created from the lists, dictionary, and from a list of dictionaries, etc.
import pandas as pd
# Calling DataFrame constructor
df = pd.DataFrame()
print(df)
# list of strings
lst = [['This', 'is', 'GMR', ],['Institute', 'of' ,'Technology']]
# Calling DataFrame constructor on list
df = pd.DataFrame(lst)
print(df)

Output:

Empty DataFrame
Columns: []
Index: []
0 1 2
0 This is GMR

1 Institute of Technology

***

Notes Prepared by : Mr D Siva Krishna, Assistant Professor, Dept of CSE, GMRIT


Lecture Notes-44 Python Programming

Basic Operations on Pandas Data Frame

Basic operations that can be applied on a pandas Data Frame are as shown below.
1. Creating a Data Frame.
2. Performing operations on Rows and Columns.
3. Data Selection, addition, deletion.
4. Working with missing data.
5. Renaming the Columns or Indices of a DataFrame.

1. Creating a Data Frame

The Pandas data frame can be created by loading the data from the external, existing
storage like a database, SQL, or CSV files. But the Pandas Data Frame can also be created

from the lists, dictionary, etc.

One of the ways to create a pandas data frame is shown below:

import pandas as pd
# Dictionary of key pair values called data
data = {
'Name':['Ashika', 'Tanu', 'Ashwin', 'Mohit', 'Sourabh'],
'Age': [24, 23, 22, 19, 10]
}
df = pd.DataFrame(data)
print(df)

Output:
Name Age
0 Ashika 24
1 Tanu 23
2 Ashwin 22
3 Mohit 19
4 Sourabh 10

2. Performing operations on Rows and Columns


Data Frame is a two-dimensional data structure, data is stored in rows and columns.
Below we can perform some operations on Rows and Columns.

Notes Prepared by : Mr D Siva Krishna, Assistant Professor, Dept of CSE, GMRIT


Lecture Notes-44 Python Programming
Selecting a Column: In order to select a particular column, all we can do is just call
the name of the column inside the data frame
import pandas as pd
data = {'Name':['Ashika', 'Tanu', 'Ashwin', 'Mohit', 'Sourabh'],
'Age': [24, 23, 22, 19, 10]}
df = pd.DataFrame(data)
# Selecting column
print(df[['Name']])
Output:
Name
0 Ashika
1 Tanu
2 Ashwin
3 Mohit
4 Sourabh

Selecting a Row: Pandas Data Frame provides a method called “loc” which is used to
retrieve rows from the data frame. Also, rows can also be selected by using the “iloc”
as a function.
import pandas as pd
data = {'Name':['Ashika', 'Tanu', 'Ashwin', 'Mohit', 'Sourabh'],
'Age': [24, 23, 22, 19, 10]}

df = pd.DataFrame(data)
# Selecting a row
row = df.loc[1]
print(row)
Output:
Name Tanu
Age 23
Name: 1, dtype: object
3. Data Selection, addition, deletion.
You can treat a DataFrame semantically like a dictionary of like-indexed Series
objects. Getting, setting, and deleting columns works with the same syntax as the
analogous dictionary operations:
import pandas as pd
data = {'Name':['Ashika', 'Tanu', 'Ashwin', 'Mohit', 'Sourabh'],
'Age': [24, 23, 22, 19, 10]}

df = pd.DataFrame(data)
# Selecting the data from the column

Notes Prepared by : Mr D Siva Krishna, Assistant Professor, Dept of CSE, GMRIT


Lecture Notes-44 Python Programming
print(df['Age'])
Output:
0 24
1 23
2 22
3 19
4 10
Name: Age, dtype: int64

Columns can be deleted like with a dictionary just use the del operation.
del df[‘Age’]

Data can be added by using the insert function. The insert function is available to insert
at a particular location in the columns:
df.insert(1, ‘name’, df[‘Name’])
print(df)

4. Working with missing data.


Missing data occur a lot of times when we are accessing big data sets. It occurs often
like NaN (Not a number). In order to fill those values, we can use “isnull()” method.
This method checks whether a null value is present in a data frame or not.
Checking for the missing values.
import pandas as pd
import numpy as np
data ={‘First name’:['Tanu', np.nan],
'Age': [23, np.nan]}
df = pd.DataFrame(data)
print(df)
# using the isnull() function
print(df.isnull())
Output:
First name Age
0 Tanu 23.0
1 NaN NaN
First name Age
0 False False
1 True True
The isnull () returns false if the null is not present and true for null values. Now we
have found the missing values, the next task is to fill those values with 0 this can be
done as shown below:

print(df.fillna(0))

Output:
First name Age

Notes Prepared by : Mr D Siva Krishna, Assistant Professor, Dept of CSE, GMRIT


Lecture Notes-44 Python Programming
0 Tanu 23.0
1 0 0.0
5. Renaming the Columns or Indices of a DataFrame
To give the columns or the index values of your data frame a different value, it’s best
to use the .rename() method. Purposefully I have changed the column name to give a
better insight.

import pandas as pd
data = {‘NAMe’:[‘Ashika’, ‘Tanu’, ‘Ashwin’, ‘Mohit’, ‘Sourabh’],
‘AGe’: [24, 23, 22, 19, 10]}# Calling the pandas data frame
df = pd.DataFrame(data)
newcols = {
‘NAMe’: ‘Name’,
‘AGe’: ‘Age’
}
# Use `rename()` to rename your columns
df.rename(columns=newcols, inplace=True)
print(df)
Output:

***

Notes Prepared by : Mr D Siva Krishna, Assistant Professor, Dept of CSE, GMRIT


Lecture Notes-45 Python Programming

MORE PROGRAMMING ON NUMPY AND PANDAS

A) Write a Python program to Create a data frame from dict of numpy array.

import pandas as pd
import numpy as np

# creating the Numpy array


array = np.array([[1, 1, 1], [2, 4, 8], [3, 9, 27],
[4, 16, 64], [5, 25, 125], [6, 36, 216],
[7, 49, 343]])

# creating a list of index names


index_values = ['first', 'second', 'third',
'fourth', 'fifth', 'sixth', 'seventh']

# creating a list of column names


column_values = ['number', 'squares', 'cubes']

# creating the dataframe


df = pd.DataFrame(data = array,
index = index_values,
columns = column_values)

# displaying the dataframe


print(df)

Ouutput:

number squares cubes


first 1 1 1
second 2 4 8
third 3 9 27
fourth 4 16 64
fifth 5 25 125
sixth 6 36 216
seventh 7 49 343

B) Write a Python program to Clean the string data in the given pandas data frame.

import pandas as pd

# Create the dataframe


df = pd.DataFrame({'Date':['10/2/2011', '11/2/2011', '12/2/2011', '13/2/2011'],
'Product':[' UMbreLla', ' maTress', 'BaDmintoN ', 'Shuttle'],

Notes Prepared by : Mr D Siva Krishna, Assistant Professor, Dept of CSE, GMRIT


Lecture Notes-45 Python Programming
'Updated_Price':[1250, 1450, 1550, 400],
'Discount':[10, 8, 15, 10]})
# Print the dataframe
print(df)

df['Product'] = df['Product'].apply(lambda x : x.strip().capitalize())

print(df)

Output:
Date Product Updated_Price Discount
0 10/2/2011 UMbreLla 1250 10
1 11/2/2011 maTress 1450 8
2 12/2/2011 BaDmintoN 1550 15
3 13/2/2011 Shuttle 400 10
Date Product Updated_Price Discount
0 10/2/2011 Umbrella 1250 10
1 11/2/2011 Matress 1450 8
2 12/2/2011 Badminton 1550 15
3 13/2/2011 Shuttle 400 10

C) Write a Python program on Conditional operations on pandas data frame.

#Applying IF condition on Numbers


from pandas import DataFrame

numbers = {'mynumbers': [51, 52, 53, 54, 55]}


df = DataFrame(numbers, columns =['mynumbers'])

df.loc[df['mynumbers'] <= 53, '<= 53'] = 'True'


df.loc[df['mynumbers'] > 53, '<= 53'] = 'False'

print(df)

Output

mynumbers <= 53
0 51 True
1 52 True
2 53 True
3 54 False
4 55 False

#Applying IF condition with lambda

from pandas import DataFrame

Notes Prepared by : Mr D Siva Krishna, Assistant Professor, Dept of CSE, GMRIT


Lecture Notes-45 Python Programming
numbers = {'mynumbers': [51, 52, 53, 54, 55]}
df = DataFrame(numbers, columns =['mynumbers'])

df['<= 53'] = df['mynumbers'].apply(lambda x: 'True' if x <= 53 else 'False')

print (df)

Output:
mynumbers <= 53
0 51 True
1 52 True
2 53 True
3 54 False
4 55 False

#Applying IF condition on strings

from pandas import DataFrame

names = {'First_name': ['Hanah', 'Ria', 'Jay', 'Bholu', 'Sachin']}


df = DataFrame(names, columns =['First_name'])

df.loc[df['First_name'] == 'Ria', 'Status'] = 'Found'


df.loc[df['First_name'] != 'Ria', 'Status'] = 'Not Found'

print (df)

Output:
First_name Status
0 Hanah Not Found
1 Ria Found
2 Jay Not Found
3 Bholu Not Found
4 Sachin Not Found

#Applying IF condition with OR

from pandas import DataFrame

names = {'First_name': ['Hanah', 'Ria', 'Jay', 'Bholu', 'Sachin']}


df = DataFrame(names, columns =['First_name'])

df.loc[(df['First_name'] == 'Ria') | (df['First_name'] == 'Jay'), 'Status'] = 'Found'


df.loc[(df['First_name'] != 'Ria') & (df['First_name'] != 'Jay'), 'Status'] = 'Not Found'

print (df)

Notes Prepared by : Mr D Siva Krishna, Assistant Professor, Dept of CSE, GMRIT


Lecture Notes-45 Python Programming

Output:
First_name Status
0 Hanah Not Found
1 Ria Found
2 Jay Found
3 Bholu Not Found
4 Sachin Not Found

***

Notes Prepared by : Mr D Siva Krishna, Assistant Professor, Dept of CSE, GMRIT

You might also like