Search for notes by fellow students, in your own course and all over the country.
Browse our notes for titles which look like what you need, you can preview any of the notes via a sample of the contents. After you're happy these are the notes you're after simply pop them into your shopping cart.
Title: Python programming
Description: Python programming notes typically documentation or written materials that explain and illustrate various concepts, syntax, and best practices related to the Python programming language. These notes can cover topics ranging from the basics of Python, such as data types, variables, and control structures, to more advanced topics like object-oriented programming, web development, data analysis, and machine learning using Python. Such notes often include code examples, explanations, and practical applications to help learners understand and implement Python code effectively. They may also contain tips, tricks, and common pitfalls to watch out for while programming in Python. These resources are often utilized by beginners and experienced developers alike to deepen their understanding of Python and improve their programming skills.
Description: Python programming notes typically documentation or written materials that explain and illustrate various concepts, syntax, and best practices related to the Python programming language. These notes can cover topics ranging from the basics of Python, such as data types, variables, and control structures, to more advanced topics like object-oriented programming, web development, data analysis, and machine learning using Python. Such notes often include code examples, explanations, and practical applications to help learners understand and implement Python code effectively. They may also contain tips, tricks, and common pitfalls to watch out for while programming in Python. These resources are often utilized by beginners and experienced developers alike to deepen their understanding of Python and improve their programming skills.
Document Preview
Extracts from the notes are below, to see the PDF you'll receive please use the links above
PYTHON PROGRAMMING
III YEAR/II SEM
MRCET
PYTHON PROGRAMMING
[R17A0554]
LECTURE NOTES
B
...
of India)
Recognized under 2(f) and 12 (B) of UGC ACT 1956
(Affiliated to JNTUH, Hyderabad, Approved by AICTE - Accredited by NBA & NAAC – ‘A’ Grade - ISO 9001:2015
Certified)
Maisammaguda, Dhulapally (Post Via
...
Tech CSE -II SEM
L
3
T/P/D C
-/-/- 3
OPEN ELECTIVE III
(R17A0554) PYTHON PROGRAMMING
OBJECTIVES:
To read and write simple Python programs
...
To define Python functions and call them
...
To do input/output with files in Python
...
UNIT II
CONTROL FLOW, LOOPS
Conditionals: Boolean values and operators, conditional (if), alternative (if-else), chained conditional
(if-elif-else); Iteration: while, for, break, continue
...
UNIT IV
LISTS, TUPLES, DICTIONARIES
Lists: list operations, list slices, list methods, list loop, mutability, aliasing, cloning lists, list
parameters, list comprehension; Tuples: tuple assignment, tuple as return value, tuple comprehension;
Dictionaries: operations and methods, comprehension;
UNIT V
FILES, EXCEPTIONS, MODULES, PACKAGES
Files and exception: text files, reading and writing files, command line arguments, errors and
exceptions, handling exceptions, modules (datetime, time, OS , calendar, math module), Explore
packages
...
Structure simple Python programs for solving problems
...
Represent compound data using Python lists, tuples, dictionaries
...
Allen B
...
2
...
Nageswara Rao, “Core Python Programming”, dreamtech
3
...
Core Python Programming, W
...
2
...
Lambert, Cengage
3
...
FUNCTIONS, ARRAYS
Fruitful functions: return values
parameters
local and global scope
function composition
recursion
Strings: string slices
immutability
string functions and methods
string module
Python arrays
Access the Elements of an Array
Array methods
PAGE NO
1
1
6
7
8
8
10
11
13
16
17
18
19
20
21
26
35
35
36
37
39
41
55
55
57
59
62
63
64
66
67
72
73
75
76
PYTHON PROGRAMMING
IV
V
III YEAR/II SEM
LISTS, TUPLES, DICTIONARIES
Lists
list operations
list slices
list methods
list loop
mutability
aliasing
cloning lists
list parameters
list comprehension
Tuples
tuple assignment
tuple as return value
tuple comprehension
Dictionaries
operations and methods
comprehension
FILES, EXCEPTIONS,
MODULES, PACKAGES
Files and exception: text files
reading and writing files
command line arguments
errors and exceptions
handling exceptions
modules (datetime, time, OS , calendar,
math module)
Explore packages
MRCET
78
78
79
80
81
83
85
87
88
89
90
91
94
95
96
97
97
102
103
103
104
109
112
114
121
134
PYTHON PROGRAMMING
III YEAR/II SEM
MRCET
UNIT – I
INTRODUCTION DATA, EXPRESSIONS, STATEMENTS
Introduction to Python and installation, data types: Int, float, Boolean, string, and list;
variables, expressions, statements, precedence of operators, comments; modules, functions-- function and its use, flow of execution, parameters and arguments
...
It was initially
designed by Guido van Rossum in 1991 and developed by Python Software Foundation
...
Python is a programming language that lets you work quickly and integrate systems more
efficiently
...
• On 16 October 2000, Python 2
...
• On 3rd December 2008, Python 3
...
Beginning with Python programming:
1) Finding an Interpreter:
Before we start Python programming, we need to have an interpreter to interpret and run our
programs
...
geeksforgeeks
...
com/ or http://codepad
...
Windows: There are many interpreters available freely to run Python scripts like IDLE
(Integrated Development Environment) which is installed when you install the python
software from http://python
...
Python is object-oriented
Structure supports such concepts as polymorphism, operation overloading and
multiple inheritance
...
Indentation
Indentation is one of the greatest feature in python
2
PYTHON PROGRAMMING
III YEAR/II SEM
MRCET
3
...
It’s Powerful
Dynamic typing
Built-in types and tools
Library utilities
Third party utilities (e
...
Numeric, NumPy, sciPy)
Automatic memory management
5
...
6
...
This gives python the development speed of an interpreter without the
performance loss inherent in purely interpreted languages
...
7
...
Interactive Programming Language
Users can interact with the python interpreter directly for writing the programs
9
...
Installation:
There are many interpreters available freely to run Python scripts like IDLE (Integrated
Development Environment) which is installed when you install the python software
from http://python
...
Step 2: Download Python Executable Installer
...
Step 4: Verify Python Was Installed On Windows
...
Step 6: Add Python Path to Environment Variables (Optional)
Working with Python
Python Code Execution:
Python’s traditional runtime execution model: Source code you type is translated to byte
code, which is then run by the Python Virtual Machine (PVM)
...
Source
Byte code
m
...
pyc
Runtime
Source code extension is
...
pyc (Compiled python code)
There are two modes for using the Python interpreter:
• Interactive Mode
• Script Mode
4
PVM
PYTHON PROGRAMMING
III YEAR/II SEM
MRCET
Running Python in interactive mode:
Without passing python script file to the interpreter, directly execute code to Python prompt
...
>>> print("hello world")
hello world
# Relevant output is displayed on subsequent lines without the >>> symbol
>>> x=[0,1,2]
# Quantities stored in memory are not displayed by default
...
[0, 1, 2]
>>> 2+3
5
The chevron at the beginning of the 1st line, i
...
, the symbol >>> is a prompt the python
interpreter uses to indicate that it is ready
...
Running Python in script mode:
5
PYTHON PROGRAMMING
III YEAR/II SEM
MRCET
Alternatively, programmers can store Python script source code in a file with
the
...
To execute the
script by the interpreter, you have to tell the interpreter the name of the file
...
py and you're working on Unix, to run the script you have to
type:
python MyFile
...
Example:
Data types:
The data stored in memory can be of many types
...
Python
has various standard data types that are used to define the operations possible on them and
the storage method for each of them
...
>>> print(24656354687654+2)
24656354687656
>>> print(20)
20
>>> print(0b10)
2
6
without decimals, of unlimited
PYTHON PROGRAMMING
III YEAR/II SEM
MRCET
>>> print(0B10)
2
>>> print(0X20)
32
>>> 20
20
>>> 0b10
2
>>> a=10
>>> print(a)
10
# To verify the type of any object in Python, use the type() function:
>>> type(10)
>>> a=11
>>> print(type(a))
Float:
Float, or "floating point number" is a number, positive or negative, containing one or more
decimals
...
>>> y=2
...
8
>>> y=2
...
4)
>>> 2
...
0
Example:
x = 35e3
y = 12E4
z = -87
...
Strings in Python are identified as a contiguous set of characters represented in the
quotation marks
...
• 'hello' is the same as "hello"
...
For example: print("hello")
...
If a string is to contain a single quote, delimit it with
double quotes and vice versa:
>>> print("mrcet is an autonomous (') college")
mrcet is an autonomous (') college
>>> print('mrcet is an autonomous (") college')
mrcet is an autonomous (") college
Suppressing Special Character:
Specifying a backslash (\) in front of the quote character in a string “escapes” it and causes
Python to suppress its usual special meaning
...
b')
a
...
(Grow and shrink as needed, sequence type, sortable)
...
Do this using square brackets and separate
values with commas
...
Ex:
>>> list1=[1,2,3,'A','B',7,8,[10,11]]
>>> print(list1)
[1, 2, 3, 'A', 'B', 7, 8, [10, 11]]
10
PYTHON PROGRAMMING
III YEAR/II SEM
MRCET
--------------------->>> x=list()
>>> x
[]
------------------------->>> tuple1=(1,2,3,4)
>>> x=list(tuple1)
>>> x
[1, 2, 3, 4]
Variables:
Variables are nothing but reserved memory locations to store values
...
Based on the data type of a variable, the interpreter allocates memory and decides what can
be stored in the reserved memory
...
Rules for Python variables:
• A variable name must start with a letter or the underscore character
• A variable name cannot start with a number
• A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9,
and _ )
• Variable names are case-sensitive (age, Age and AGE are three different variables)
Assigning Values to Variables:
Python variables do not need explicit declaration to reserve memory space
...
The equal sign (=) is used to
assign values to variables
...
11
PYTHON PROGRAMMING
III YEAR/II SEM
MRCET
For example −
a= 100
# An integer assignment
b = 1000
...
0
John
Multiple Assignment:
Python allows you to assign a single value to several variables simultaneously
...
You can also assign multiple objects to multiple variables
...
Output Variables:
The Python print statement is often used to output variables
...
12
PYTHON PROGRAMMING
x=5
x = "mrcet "
print(x)
III YEAR/II SEM
MRCET
# x is of type int
# x is now of type str
Output: mrcet
To combine both text and a variable, Python uses the “+” character:
Example
x = "awesome"
print("Python is " + x)
Output
Python is awesome
You can also use the + character to add a variable to another variable:
Example
x = "Python is "
y = "awesome"
z=x+y
print(z)
Output:
Python is awesome
Expressions:
An expression is a combination of values, variables, and operators
...
Examples: Y=x + 17
>>> x=10
>>> z=x+20
>>> z
30
13
PYTHON PROGRAMMING
III YEAR/II SEM
MRCET
>>> x=10
>>> y=20
>>> c=x+y
>>> c
30
A value all by itself is a simple expression, and so is a variable
...
So,
Identifiers: Any name that is used to define a class, function, variable module, or object is
an identifier
...
In Python, there are the string literals, byte literals, integer
literals, floating point literals, and imaginary literals
...
14
PYTHON PROGRAMMING
III YEAR/II SEM
MRCET
Operator
Token
add
+
subtract
-
multiply
*
Integer Division
/
remainder
%
Binary left shift
<<
Binary right shift
>>
and
&
or
\
Less than
<
Greater than
>
Less than or equal to
<=
Greater than or equal to
>=
Check equality
==
Check not equal
!=
15
PYTHON PROGRAMMING
III YEAR/II SEM
MRCET
Some of the python expressions are:
Generator expression:
Syntax: ( compute(var) for var in iterable )
>>> x = (i for i in 'abc') #tuple comprehension
>>> x
>>> print(x)
You might expect this to print as ('a', 'b', 'c') but it prints as
at 0x02AAD710> The result of a tuple comprehension is not a tuple: it is actually a
generator
...
Conditional expression:
Syntax: true_value if Condition else false_value
>>> x = "1" if True else "2"
>>> x
'1'
Statements:
A statement is an instruction that the Python interpreter can execute
...
Some other kinds of
statements that are if statements, while statements, and for statements generally called as
control flows
...
>>> print("mrcet colege")
mrcet college
Precedence of Operators:
Operator precedence affects how an expression is evaluated
...
Example 1:
>>> 3+4*2
11
Multiplication gets evaluated before the addition operation
>>> (10+10)*2
40
Parentheses () overriding the precedence of the arithmetic operators
Example 2:
a = 20
b = 10
c = 15
d=5
e=0
e = (a + b) * c / d
#( 30 * 15 ) / 5
print("Value of (a + b) * c / d is ", e)
e = ((a + b) * c) / d # (30 * 15 ) / 5
print("Value of ((a + b) * c) / d is ", e)
e = (a + b) * (c / d); # (30) * (15/5)
17
PYTHON PROGRAMMING
III YEAR/II SEM
MRCET
print("Value of (a + b) * (c / d) is ", e)
e = a + (b * c) / d; # 20 + (150/5)
print("Value of a + (b * c) / d is ", e)
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/opprec
...
0
Value of ((a + b) * c) / d is 90
...
0
Value of a + (b * c) / d is 50
...
A Multi line comment is useful when we need to comment on many lines
...
Example:
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/comm
...
In other words, we can say that our
python code file saved with the extension (
...
We may have a
runnable code inside the python module
...
To use the functionality of one module into another, we
must have to import the specific module
...
(dot)
Note: In python we have help ()
Enter the name of any module, keyword, or topic to get help on writing Python programs
and using Python modules
...
Some of the modules like os, date, and calendar so on……
>>> import sys
>>> print(sys
...
8
...
8
...
1916 32 bit (Intel)]
>>> print(sys
...
version_info(major=3, minor=8, micro=0, releaselevel='final', serial=0)
>>> print(calendar
...
isleap(2020))
True
>>> print(calendar
...
Functions help break our program into smaller and modular chunks
...
It avoids repetition and
makes code reusable
...
Built-in functions - Functions that are built into Python
...
ascii(),bool()………so on…
...
User-defined functions - Functions defined by the users themselves
...
2
...
4
...
Statements are executed one at a time, in order, from top to bottom
...
5
...
Instead of going to the next
statement, the flow jumps to the first line of the called function, executes all the
statements there, and then comes back to pick up where it left off
...
Instead, follow the flow of
execution
...
Example:
#example for flow of execution
print("welcome")
for x in range(3):
print(x)
print("Good morning college")
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/flowof
...
py
hi
hello
Good morning
mrcet
done!
The flow/order of execution is: 2,5,6,7,2,3,4,7,8
Parameters and arguments:
Parameters are passed during the definition of function while Arguments are passed during
the function call
...
py
25
There are three types of Python function arguments using which we can call a function
...
Default Arguments
2
...
Variable-length Arguments
Syntax:
def functionname():
22
PYTHON PROGRAMMING
III YEAR/II SEM
MRCET
statements
...
...
Keyword def indicates the start of function header
...
A function name to uniquely identify it
...
3
...
They are optional
...
A colon (:) to mark the end of function header
...
Optional documentation string (docstring) to describe what the function does
...
One or more valid python statements that make up the function body
...
7
...
Example:
def hf():
hello world
hf()
In the above example we are just trying to execute the program by calling the function
...
To get the statements of function need to be use print()
...
This statement can contain expression which gets evaluated and the value is returned
...
def hf():
return "hw"
print(hf())
Output:
hw
----------------------------
def hf():
return "hw"
hf()
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/fu
...
upper())
Output:
HELLOCOLLEGE
# Passing Arguments
def hello(wish):
return '{}'
...
Since, we have called this function with two
arguments, it runs smoothly and we do not get any error
...
def wish(name,msg):
"""This function greets to
the person with the provided message"""
print("Hello",name + ' ' + msg)
wish("MRCET","Good morning!")
Output:
Hello MRCET Good morning!
26
PYTHON PROGRAMMING
III YEAR/II SEM
MRCET
Below is a call to this function with one and no arguments along with their respective error
messages
...
format(wish,hello)
print(hello("mrcet","college"))
Output:
himrcet,college
#Keyword Arguments
When we call a function with some values, these values get assigned to the arguments
according to their position
...
When we call functions in
this way, the order (position) of the arguments can be changed
...
There are two advantages - one, using the function is easier since we do not need to
worry about the order of the arguments
...
def func(a, b=5, c=10):
print 'a is', a, 'and b is', b, 'and c is', c
27
PYTHON PROGRAMMING
III YEAR/II SEM
MRCET
func(3, 7)
func(25, c=24)
func(c=50, a=100)
Output:
a is 3 and b is 7 and c is 10
a is 25 and b is 5 and c is 24
a is 100 and b is 5 and c is 50
Note:
The function named func has one parameter without default argument values,
followed by two parameters with default argument values
...
In the second usage func(25, c=24), the variable a gets the value of 25 due to the
position of the argument
...
e
...
The variable b gets the default value of 5
...
Notice, that we are specifying value for parameter c before that
for a even though a is defined before c in the function definition
...
We can provide a default value to an argument by using the assignment operator (=)
def hello(wish,name='you'):
return '{},{}'
...
format(wish,name)
//print(wish + ‘ ‘ + name)
print(hello("good morning","nirosha")) // hello("good morning","nirosha")
Output:
good morning,nirosha //
good morning nirosha
Note: Any number of arguments in a function can have a default value
...
This means to say, non-default arguments cannot follow default arguments
...
If we don’t know in advance about the arguments needed in function, we can use
variable-length arguments also called arbitrary arguments
...
If we use one asterisk (*) like *var, then all the positional arguments from that point till the
end are collected as a tuple called ‘var’ and if we use two asterisks (**) before a variable like
**var, then all the positional arguments from that point till the end are collected as
a dictionary called ‘var’
...
"""
# names is a tuple with arguments
for name in names:
print("Hello",name)
wish("MRCET","CSE","SIR","MADAM")
30
PYTHON PROGRAMMING
III YEAR/II SEM
MRCET
Output:
Hello MRCET
Hello CSE
Hello SIR
Hello MADAM
#Program to find area of a circle using function use single return value function with
argument
...
14
def areaOfCircle(r):
return pi*r*r
r=int(input("Enter radius of circle"))
print(areaOfCircle(r))
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/fu1
...
259999999999998
#Program to write sum different product and using arguments with return value
function
...
py
Enter a value 5
Enter b value 6
Sum= 11 diff= -1 mul= 30 div= 0
...
def biggest(a,b):
if a>b :
return a
else :
return b
a=int(input("Enter a value"))
b=int(input("Enter b value"))
#function call
big= biggest(a,b)
print("big number= ",big)
Output:
32
MRCET
PYTHON PROGRAMMING
III YEAR/II SEM
MRCET
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/fu1
...
(nested if)
def biggest(a,b,c):
if a>b :
if a>c :
return a
else :
return c
else :
if b>c :
return b
else :
return c
a=int(input("Enter a value"))
b=int(input("Enter b value"))
c=int(input("Enter c value"))
#function call
big= biggest(a,b,c)
print("big number= ",big)
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/fu1
...
def result(a):
if a>40:
return "pass"
33
PYTHON PROGRAMMING
III YEAR/II SEM
MRCET
else:
return "fail"
a=int(input("Enter one subject marks"))
print(result(a))
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/fu1
...
(while loop)
def usingFunctions():
count =0
while count<10:
print("mrcet cse dept",count)
count=count+1
usingFunctions()
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/fu1
...
Control Flow, Loops:
Boolean Values and Operators:
A boolean expression is an expression that is either true or false
...
Syntax:
if expression:
statement(s)
If the boolean expression evaluates to TRUE, then the block of statement(s) inside the if
statement is executed
...
if Statement Flowchart:
Fig: Operation of if statement
Example: Python if Statement
a=3
if a > 2:
print(a, "is greater")
print("done")
a = -1
if a < 0:
print(a, "a is smaller")
print("Finish")
Output:
36
PYTHON PROGRAMMING
III YEAR/II SEM
MRCET
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/if1
...
py
A is Greater than 9
Alternative if (If-Else):
An else statement can be combined with an if statement
...
The else statement is an optional statement and there could be at most only one else
Statement following if
...
py
enter the number 2
a is smaller than the input given
---------------------------------------a=10
b=20
if a>b:
print("A is Greater than B")
else:
print("B is Greater than A")
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/if2
...
Similar to the else,
the elif statement is optional
...
Syntax of if – elif - else :
If test expression:
Body of if stmts
elif test expression:
Body of elif stmts
else:
Body of else stmts
Flowchart of if – elif - else:
Fig: Operation of if – elif - else statement
Example of if - elif – else:
a=int(input('enter the number'))
b=int(input('enter the number'))
c=int(input('enter the number'))
if a>b:
39
PYTHON PROGRAMMING
III YEAR/II SEM
print("a is greater")
elif b>c:
print("b is greater")
else:
print("c is greater")
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/ifelse
...
py
enter the number2
enter the number5
enter the number9
c is greater
----------------------------var = 100
if var == 200:
print("1 - Got a true expression value")
print(var)
elif var == 150:
print("2 - Got a true expression value")
print(var)
elif var == 100:
print("3 - Got a true expression value")
print(var)
else:
print("4 - Got a false expression value")
print(var)
print("Good bye!")
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/ifelif
...
Repeated execution of a set of statements with the help of loops
is called iteration
...
Statements:
In Python Iteration (Loops) statements are of three types:
1
...
For Loop
3
...
Python while loop keeps reiterating a block of
code defined inside it until the desired condition is met
...
The statements that are executed inside while can be a single line of code or a block of
multiple statements
...
-------------------------------------i=1
while i<=6:
print("Mrcet college")
i=i+1
output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/wh1
...
----------------------------------------------------i=1
while i<=3:
print("MRCET",end=" ")
j=1
while j<=1:
print("CSE DEPT",end="")
j=j+1
i=i+1
print()
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/wh2
...
-------------------------------------------------i=1
42
MRCET
PYTHON PROGRAMMING
III YEAR/II SEM
j=1
while i<=3:
print("MRCET",end=" ")
while j<=1:
print("CSE DEPT",end="")
j=j+1
i=i+1
print()
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/wh3
...
---------------------------------------i=1
while (i < 10):
print (i)
i = i+1
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/wh4
...
--------------------------------------a=1
b=1
while (a<10):
print ('Iteration',a)
a=a+1
b=b+1
43
MRCET
PYTHON PROGRAMMING
III YEAR/II SEM
MRCET
if (b == 4):
break
print ('While loop terminated')
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/wh5
...
py =
The count is: 0
The count is: 1
The count is: 2
The count is: 3
The count is: 4
The count is: 5
The count is: 6
The count is: 7
The count is: 8
Good bye!
For loop:
Python for loop is used for repeated execution of a group of statements for the desired
number of times
...
py
1
4
16
36
121
400
Flowchart:
45
MRCET
PYTHON PROGRAMMING
III YEAR/II SEM
Iterating over a list:
#list of items
list = ['M','R','C','E','T']
i=1
#Iterating over the list
for item in list:
print ('college ',i,' is ',item)
i = i+1
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/lis
...
py
These are the first four prime numbers
2
3
5
7
Iterating over a dictionary:
#creating a dictionary
college = {"ces":"block1","it":"block2","ece":"block3"}
#Iterating over the dictionary to print keys
print ('Keys are:')
46
MRCET
PYTHON PROGRAMMING
III YEAR/II SEM
for keys in college:
print (keys)
#Iterating over the dictionary to print values
print ('Values are:')
for blocks in college
...
py
Keys are:
ces
it
ece
Values are:
block1
block2
block3
Iterating over a String:
#declare a string to iterate over
college = 'MRCET'
#Iterating over the string
for name in college:
print (name)
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/strr
...
Syntax:
for val in sequence:
for val in sequence:
47
MRCET
PYTHON PROGRAMMING
III YEAR/II SEM
statements
statements
# Example 1 of Nested For Loops (Pattern Programs)
for i in range(1,6):
for j in range(0,i):
print(i, end=" ")
print('')
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/nesforr
...
py
Output:
11111
2222
333
44
48
MRCET
PYTHON PROGRAMMING
III YEAR/II SEM
MRCET
Break and continue:
In Python, break and continue statements can alter the flow of a normal loop
...
The break and continue statements are used in these cases
...
If break statement is inside a nested
loop (loop inside another loop), break will terminate the innermost loop
...
py =
Current Letter : P
Current Letter : y
Current Letter : t
Continue:
The continue statement is used to skip the rest of the code inside a loop for the current
iteration only
...
Flowchart:
The following shows the working of break statement in for and while loop:
51
PYTHON PROGRAMMING
III YEAR/II SEM
for var in sequence:
# code inside for loop
If condition:
continue (if break condition satisfies it jumps to outside loop)
# code inside for loop
# code outside for loop
while test expression
# code inside while loop
If condition:
continue(if break condition satisfies it jumps to outside loop)
# code inside while loop
# code outside while loop
Example:
# Program to show the use of continue statement inside loops
for val in "string":
if val == "i":
continue
print(val)
print("The end")
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/cont
...
py
11
9
89
#-----------------for letter in "Python": # First Example
if letter == "h":
continue
print("Current Letter :", letter)
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/con1
...
The difference between
a comment and pass statement in Python is that, while the interpreter ignores a comment
entirely, pass is not ignored
...
Example:
sequence = {'p', 'a', 's', 's'}
for val in sequence:
pass
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/f1
...
py
53
PYTHON PROGRAMMING
III YEAR/II SEM
>>>
Similarily we can also write,
def f(arg): pass # a function that does nothing (yet)
class C: pass
# a class with no methods (yet)
54
MRCET
PYTHON PROGRAMMING
III YEAR/II SEM
MRCET
UNIT – III
FUNCTIONS, ARRAYS
Fruitful functions: return values, parameters, local and global scope, function composition,
recursion; Strings: string slices, immutability, string functions and methods, string module;
Python arrays, Access the Elements of an Array, array methods
...
We have seen
the return statement before, but in a fruitful function the return statement includes a return
value
...
"
(or)
Any function that returns a value is called Fruitful function
...
# returns the area of a circle with the given radius:
def area(radius):
temp = 3
...
14 * radius**2
print(area(2))
Sometimes it is useful to have multiple return statements, one in each branch of a
conditional:
def absolute_value(x):
if x < 0:
55
PYTHON PROGRAMMING
III YEAR/II SEM
MRCET
return -x
else:
return x
Since these return statements are in an alternative conditional, only one will be executed
...
Code that appears after a return statement, or any other place the
flow of execution can never reach, is called dead code
...
For example:
def absolute_value(x):
if x < 0:
return -x
if x > 0:
return x
This function is incorrect because if x happens to be 0, both conditions is true, and the
function ends without hitting a return statement
...
>>> print absolute_value(0)
None
By the way, Python provides a built-in function called abs that computes absolute values
...
def common_data(list1, list2):
for x in list1:
for y in list2:
if x == y:
result = True
return result
print(common_data([1,2,3,4,5], [1,2,3,4,5]))
print(common_data([1,2,3,4,5], [1,7,8,9,510]))
print(common_data([1,2,3,4,5], [6,7,8,9,10]))
Output:
C:\Users\MRCET\AppData\Local\Programs\Python\Python38-32\pyyy\fu1
...
14159 * radius**2
return b
Parameters:
Parameters are passed during the definition of function while Arguments are passed during
the function call
...
py
25
Some examples on functions:
# To display vandemataram by using function use no args no return type
#function defination
def display():
print("vandemataram")
print("i am in main")
57
PYTHON PROGRAMMING
III YEAR/II SEM
#function call
display()
print("i am in main")
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/fu1
...
py
function 1
#Type 2: with param with out return type
def fun2(a) :
print(a)
fun2("hello")
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/fu1
...
py
welcome to python
#Type 4: with param with return type
def fun4(a):
return a
print(fun4("python is better then c"))
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/fu1
...
It is accessible from
the point at which it is defined until the end of the function, and exists for as long as the
function is executing
Global Scope:
A variable which is defined in the main body of a file is called a global variable
...
The variable defined inside a function can also be made global by using the global
statement
...
global x
#declaring global variable inside a function
...
py
x inside : global
x outside: global
# create a local variable
def f1():
y = "local"
print(y)
f1()
Output:
local
If we try to access the local variable outside the scope for example,
def f2():
y = "local"
f2()
print(y)
Then when we try to run it shows an error,
Traceback (most recent call last):
File "C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/fu1
...
# use local and global variables in same code
x = "global"
def f3():
global x
y = "local"
x=x*2
print(x)
print(y)
f3()
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/fu1
...
Then,
we use multiplication operator * to modify the global variable x and we print
both x and y
...
After that, we print the value of local variable y i
...
# use Global variable and Local variable with same name
x=5
def f4():
x = 10
print("local x:", x)
f4()
print("global x:", x)
61
PYTHON PROGRAMMING
III YEAR/II SEM
MRCET
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/fu1
...
So
for example if you have two functions FunctionA and FunctionB you compose them by
doing the following
...
Example 1:
#create a function compose2
>>> def compose2(f, g):
return lambda x:f(g(x))
>>> def d(x):
return x*2
>>> def e(x):
return x+1
>>> a=compose2(d,e) # FunctionC = compose(FunctionB,FunctionA)
>>> a(5)
# FunctionC(x)
12
In the above program we tried to compose n functions with the main function created
...
Python Recursive Function
We know that in Python, a function can call other functions
...
These type of construct are termed as recursive functions
...
For example,
the factorial of 6 (denoted as 6!) is 1*2*3*4*5*6 = 720
...
# Write a program to factorial using recursion
def fact(x):
if x==0:
result = 1
else :
result = x * fact(x-1)
return result
print("zero factorial",fact(0))
print("five factorial",fact(5))
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/rec
...
py
The factorial of 4 is 24
Strings:
A string is a group/ a sequence of characters
...
This is how we declare a string
...
Every string object is of the type ‘str’
...
The
expression in brackets is called an index
...
Selecting a slice is similar to selecting a character:
Subsets of strings can be taken using the slice operator ([ ] and [:]) with indexes starting at 0
in the beginning of the string and working their way from -1 at the end
...
Syntax:[Start: stop: steps]
Slicing will start from index and will go up to stop in step of steps
...
For example:
>>> greeting='mrcet college!'
>>> greeting[0]='n'
TypeError: 'str' object does not support item assignment
The reason for the error is that strings are immutable, which means we can’t change an
existing string
...
S
...
Method name
isalnum()
2
...
isdigit()
4
...
isnumeric()
6
...
istitle()
8
...
replace(old, new
[, max])
10
...
count()
12
...
swapcase()
14
...
Returns true if string has at least 1 character and all
characters are alphabetic and false otherwise
...
Returns true if string has at least 1 cased character and all cased
characters are in lowercase and false
otherwise
...
Returns true if string contains only whitespace
characters and false otherwise
...
Returns true if string has at least one cased character and all
cased characters are in uppercase
and false otherwise
...
Splits string according to delimiter str (space if not
provided) and returns list of substrings;
Occurrence of a string in another string
Finding the index of the first occurrence of a string
in another string
Converts lowercase letters in a string to uppercase
and viceversa
Determines if string or a substring of string (if starting index
beg and ending index end are given) starts with substring str;
returns true if so and false
otherwise
...
isalnum():
67
PYTHON PROGRAMMING
III YEAR/II SEM
MRCET
Isalnum() method returns true if string has at least 1 character and all characters are
alphanumeric and false otherwise
...
isalnum()
Example:
>>> string="123alpha"
>>> string
...
isalpha():
isalpha() method returns true if string has at least 1 character and all characters are
alphabetic and false otherwise
...
isalpha()
Example:
>>> string="nikhil"
>>> string
...
isdigit():
isdigit() returns true if string contains only digits and false otherwise
...
isdigit()
Example:
>>> string="123456789"
>>> string
...
islower():
Islower() returns true if string has characters that are in lowercase and false otherwise
...
islower()
Example:
>>> string="nikhil"
>>> string
...
isnumeric():
isnumeric() method returns true if a string contains only numeric characters and false
otherwise
...
isnumeric()
Example:
>>> string="123456789"
>>> string
...
isspace():
isspace() returns true if string contains only whitespace characters and false otherwise
...
isspace()
Example:
>>> string=" "
>>> string
...
istitle()
istitle() method returns true if string is properly “titlecased”(starting letter of each word is
capital) and false otherwise
Syntax:
String
...
istitle()
True
8
...
Syntax:
String
...
isupper()
True
9
...
Syntax:
String
...
replace('Nikhil','Neha')
'Neha Is Learning'
10
...
split()
Example:
>>> string="Nikhil Is Learning"
>>> string
...
count()
count() method counts the occurrence of a string in another string Syntax:
String
...
count('i')
3
12
...
find(„string‟)
Example:
>>> string="Nikhil Is Learning"
>>> string
...
swapcase()
converts lowercase letters in a string to uppercase and viceversa
Syntax:
String
...
swapcase()
'hello'
14
...
71
PYTHON PROGRAMMING
III YEAR/II SEM
MRCET
Syntax:
String
...
startswith('N')
True
15
...
Syntax:
String
...
startswith('g')
True
String module:
This module contains a number of functions to process standard Python strings
...
It’s a built-in module and we have to import it before using any of its constants and classes
Syntax: import string
Note:
help(string) --- gives the information about all the variables ,functions, attributes and classes
to be used in string module
...
ascii_letters)
print(string
...
ascii_uppercase)
print(string
...
hexdigits)
#print(string
...
punctuation)
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/strrmodl
...
/:;<=>?@[\]^_`{|}~
Python String Module Classes
Python string module contains two classes – Formatter and Template
...
format() function
...
Syntax: from string import Formatter
Template
This class is used to create a string template for simpler string substitutions
Syntax: from string import Template
Python arrays:
Array is a container which can hold a fix number of items and these items should be of the
same type
...
Following are the important terms to understand the concept of Array
...
Index − Each location of an element in an array has a numerical index, which is used
to identify the element
...
Below is an illustration
...
Index starts with 0
...
Each element can be accessed via its index
...
Traverse − print all the array elements one by one
...
Deletion − Deletes an element at the given index
...
Update − Updates an element at the given index
...
Then the
array is declared as shown below
...
Some
common typecodes used are:
Typecode
Value
b
Represents signed integer of size 1 byte/td>
B
Represents unsigned integer of size 1 byte
74
PYTHON PROGRAMMING
c
III YEAR/II SEM
Represents character of size 1 byte
i
Represents signed integer of size 2 bytes
I
Represents unsigned integer of size 2 bytes
f
Represents floating point of size 4 bytes
d
Represents floating point of size 8 bytes
MRCET
Creating an array:
from array import *
array1 = array('i', [10,20,30,40,50])
for x in array1:
print(x)
Output:
>>>
RESTART: C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/arr
...
from array import *
array1 = array('i', [10,20,30,40,50])
print (array1[0])
print (array1[2])
75
PYTHON PROGRAMMING
III YEAR/II SEM
MRCET
Output:
RESTART: C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/arr2
...
Method
Description
append() Adds an element at the end of the list
clear()
Removes all the elements from the list
copy()
Returns a copy of the list
count()
Returns the number of elements with the specified value
extend()
Add the elements of a list (or any iterable), to the end of the current list
index()
Returns the index of the first element with the specified value
insert()
Adds an element at the specified position
pop()
Removes the element at the specified position
remove() Removes the first item with the specified value
reverse() Reverses the order of the list
sort()
Sorts the list
76
PYTHON PROGRAMMING
III YEAR/II SEM
MRCET
Note: Python does not have built-in support for Arrays, but Python Lists can be used instead
...
append("autonomous")
>>> college
['mrcet', 'it', 'cse', 'autonomous']
>>> college
...
append("ece")
>>> college
['mrcet', 'it', 'cse', 'autonomous', 'eee', 'ece']
>>> college
...
pop(4)
'eee'
>>> college
['mrcet', 'it', 'cse', 'autonomous']
>>> college
...
(Grow and shrink as needed, sequence type, sortable)
...
Do this using square brackets and separate
values with commas
...
Ex:
>>> list1=[1,2,3,'A','B',7,8,[10,11]]
>>> print(list1)
[1, 2, 3, 'A', 'B', 7, 8, [10, 11]]
--------------------->>> x=list()
>>> x
[]
------------------------->>> tuple1=(1,2,3,4)
>>> x=list(tuple1)
>>> x
[1, 2, 3, 4]
78
PYTHON PROGRAMMING
III YEAR/II SEM
MRCET
List operations:
These operations include indexing, slicing, adding, multiplying, and checking for
membership
Basic List Operations:
Lists respond to the + and * operators much like strings; they mean concatenation and
repetition here too, except that the result is a new list, not a string
...
Assuming following input −
L = ['mrcet', 'college', 'MRCET!']
Python Expression
Results
Description
L[2]
MRCET
Offsets start at zero
79
PYTHON PROGRAMMING
III YEAR/II SEM
L[-2]
college
Negative: count from the right
L[1:]
['college', 'MRCET!']
Slicing fetches sections
MRCET
List slices:
>>> list1=range(1,6)
>>> list1
range(1, 6)
>>> print(list1)
range(1, 6)
>>> list1=[1,2,3,4,5,6,7,8,9,10]
>>> list1[1:]
[2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> list1[:1]
[1]
>>> list1[2:5]
[3, 4, 5]
>>> list1[:6]
[1, 2, 3, 4, 5, 6]
>>> list1[1:2:4]
[2]
>>> list1[1:8:2]
[2, 4, 6, 8]
List methods:
The list data type has some more methods
...
append(10)
>>> x
[1, 5, 8, 4, 10]
Extend: Append a sequence to a list
...
extend(y)
>>> x
[1, 2, 3, 4, 3, 6, 9, 1]
Insert: To add an item at the specified index, use the insert () method:
>>> x=[1,2,4,6,7]
81
MRCET
PYTHON PROGRAMMING
III YEAR/II SEM
MRCET
>>> x
...
insert(4,['a',11])
>>> x
[1, 2, 10, 4, ['a', 11], 6, 7]
Pop: The pop() method removes the specified index, (or the last item if index is not
specified) or simply pops the last item of list and returns the item
...
pop()
7
>>> x
[1, 2, 10, 4, 6]
---------------------------------->>> x=[1, 2, 10, 4, 6]
>>> x
...
>>> x=[1,33,2,10,4,6]
>>> x
...
remove(4)
>>> x
[1, 2, 10, 6]
Reverse: Reverse the order of a given list
...
reverse()
>>> x
[7, 6, 5, 4, 3, 2, 1]
Sort: Sorts the elements in ascending order
>>> x=[7, 6, 5, 4, 3, 2, 1]
>>> x
...
sort()
>>> x
[1, 3, 5, 7, 8, 10]
List loop:
Loops are control structures used to repeat a given section of code a certain number of times
or until a particular condition is met
...
py
college 1 is M
college 2 is R
college 3 is C
college 4 is E
college 5 is T
Method #2: For loop and range()
In case we want to use the traditional for loop which iterates from number x to number y
...
py
1
3
5
7
9
Method #3: using while loop
# Python3 code to iterate over a list
list = [1, 3, 5, 7, 9]
# Getting length of list
84
PYTHON PROGRAMMING
III YEAR/II SEM
length = len(list)
i=0
# Iterating using while loop
while i < length:
print(list[i])
i += 1
Mutability:
A mutable object can be changed after it is created, and an immutable object can't
...
append(10)
>>> x
[1, 5, 8, 4, 10]
Extend: Append a sequence to a list
...
extend(y)
>>> x
Delete: Delete a list or an item from a list
>>> x=[5,3,8,6]
>>> del(x[1])
#deletes the index position 1 in a list
>>> x
[5, 8, 6]
Insert: To add an item at the specified index, use the insert () method:
>>> x=[1,2,4,6,7]
>>> x
...
insert(4,['a',11])
>>> x
[1, 2, 10, 4, ['a', 11], 6, 7]
Pop: The pop() method removes the specified index, (or the last item if index is not
specified) or simply pops the last item of list and returns the item
...
pop()
7
>>> x
[1, 2, 10, 4, 6]
---------------------------------->>> x=[1, 2, 10, 4, 6]
>>> x
...
>>> x=[1,33,2,10,4,6]
>>> x
...
remove(4)
>>> x
[1, 2, 10, 6]
Reverse: Reverse the order of a given list
...
reverse()
>>> x
[7, 6, 5, 4, 3, 2, 1]
Sort: Sorts the elements in ascending order
>>> x=[7, 6, 5, 4, 3, 2, 1]
>>> x
...
sort()
>>> x
[1, 3, 5, 7, 8, 10]
Aliasing:
1
...
2
...
3
...
4
...
For ex:
a = [81, 82, 83]
87
PYTHON PROGRAMMING
III YEAR/II SEM
MRCET
b = [81, 82, 83]
print(a == b)
print(a is b)
b=a
print(a == b)
print(a is b)
b[0] = 5
print(a)
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/alia
...
Changes
made with one alias affect the other
...
Cloning Lists:
If we want to modify a list and also keep a copy of the original, we need to be able to make a
copy of the list itself, not just the reference
...
The easiest way to clone a list is to use the slice operator
...
In this case the slice happens to consist of the whole list
...
py
True
False
[81, 82, 83]
[5, 82, 83]
Now we are free to make changes to b without worrying about a
List parameters:
Passing a list as an argument actually passes a reference to the list, not a copy of the list
...
# for example, the function below takes a list as an argument and multiplies each element in
the list by 2:
def doubleStuff(List):
""" Overwrite each element in aList with double its value
...
py ==
[2, 5, 9]
[4, 10, 18]
89
PYTHON PROGRAMMING
III YEAR/II SEM
MRCET
List comprehension:
List:
List comprehensions provide a concise way to create lists
...
For example, assume we want to create a list of squares, like:
>>> list1=[]
>>> for x in range(10):
list1
...
>>> list1=[x**2 for x in range(10)]
>>> list1
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
90
PYTHON PROGRAMMING
III YEAR/II SEM
MRCET
Similarily some examples:
>>> x=[m for m in range(8)]
>>> print(x)
[0, 1, 2, 3, 4, 5, 6, 7]
>>> x=[z**2 for z in range(10) if z>4]
>>> print(x)
[25, 36, 49, 64, 81]
>>> x=[x ** 2 for x in range (1, 11) if x % 2 == 1]
>>> print(x)
[1, 9, 25, 49, 81]
>>> a=5
>>> table = [[a, b, a * b] for b in range(1, 11)]
>>> for i in table:
print(i)
[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]
Tuples:
A tuple is a collection which is ordered and unchangeable
...
Supports all operations for sequences
...
If the contents of a list shouldn’t change, use a tuple to prevent items from
91
PYTHON PROGRAMMING
III YEAR/II SEM
accidently being added, changed, or deleted
...
We can construct tuple in many ways:
X=() #no item tuple
X=(1,2,3)
X=tuple(list1)
X=1,2,3,4
Example:
>>> x=(1,2,3)
>>> print(x)
(1, 2, 3)
>>> x
(1, 2, 3)
---------------------->>> x=()
>>> x
()
--------------------------->>> x=[4,5,66,9]
>>> y=tuple(x)
>>> y
(4, 5, 66, 9)
---------------------------->>> x=1,2,3,4
>>> x
(1, 2, 3, 4)
Some of the operations of tuple are:
Access tuple items
Change tuple items
Loop through a tuple
Count()
Index()
Length()
92
MRCET
PYTHON PROGRAMMING
III YEAR/II SEM
MRCET
Access tuple items: Access tuple items by referring to the index number, inside square
brackets
>>> x=('a','b','c','g')
>>> print(x[2])
c
Change tuple items: Once a tuple is created, you cannot change its values
...
>>> x=(2,5,7,'4',8)
>>> x[1]=10
Traceback (most recent call last):
File "
x[1]=10
TypeError: 'tuple' object does not support item assignment
>>> x
(2, 5, 7, '4', 8) # the value is still the same
Loop through a tuple: We can loop the values of tuple using for loop
>>> x=4,5,6,7,2,'aa'
>>> for i in x:
print(i)
4
5
6
7
2
aa
Count (): Returns the number of times a specified value occurs in a tuple
>>> x=(1,2,3,4,5,6,2,10,2,11,12,2)
>>> x
...
index(2)
1
(Or)
>>> x=(1,2,3,4,5,6,2,10,2,11,12,2)
>>> y=x
...
>>> x=(1,2,3,4,5,6,2,10,2,11,12,2)
>>> y=len(x)
>>> print(y)
12
Tuple Assignment
Python has tuple assignment feature which enables you to assign more than one variable at a
time
...
and another tuple 2 with the values in it like number (1, 2, 3… 7)
...
It is created with or without ()
...
# A Python program to return multiple values from a method using tuple
# This function returns a tuple
def fun():
str = "mrcet college"
x = 20
return str, x; # Return tuple, we could also
# write (str, x)
# Driver code to test above method
str, x = fun() # Assign returned tuple
print(str)
print(x)
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/tupretval
...
def circleInfo(r):
""" Return (circumference, area) of a circle of radius r """
c = 2 * 3
...
14159 * r * r
return (c, a)
print(circleInfo(10))
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/functupretval
...
8318, 314
...
You
might expect it to produce a tuple, but what it does is produce a special "generator"
object that we can iterate over
...
The only thing that you need to know now about a generator now is that you
can iterate over it, but ONLY ONCE
...
In Python
dictionaries are written with curly brackets, and they have keys and values
...
Some of them have already
been used in the above examples
...
97
PYTHON PROGRAMMING
III YEAR/II SEM
copy()
Return a shallow copy of the dictionary
...
get(key[,d])
Return the value of key
...
items()
Return a new view of the dictionary's items
(key, value)
...
pop(key[,d])
Remove the item with key and return its value
or d if key is not found
...
popitem()
Remove and return an arbitary item (key,
value)
...
setdefault(key[,d])
If key is in the dictionary, return its value
...
update([other])
Update the dictionary with the key/value pairs
from other, overwriting existing keys
...
keys()
dict_keys(['brand', 'model', 'year'])
>>> dict1
...
items()
dict_items([('brand', 'mrcet'), ('model', 'college'), ('year', 2004)])
---------------------------------------------->>> for items in dict1
...
keys():
print(items)
brand
model
year
>>> for i in dict1
...
>>> dict1 = {"brand":"mrcet","model":"college","year":2004}
>>> print(dict1
...
>>> x = {1:1, 2:4, 3:9, 4:16, 5:25}
>>> del x[5]
>>> x
Length: we use len() method to get the length of dictionary
...
items():
print(k,v)
11
24
39
4 16
5 25
List of Dictionaries:
>>> customers = [{"uid":1,"name":"John"},
{"uid":2,"name":"Smith"},
{"uid":3,"name":"Andersson"},
]
>>> >>> print(customers)
[{'uid': 1, 'name': 'John'}, {'uid': 2, 'name': 'Smith'}, {'uid': 3, 'name': 'Andersson'}]
## Print the uid and name of each customer
>>> for x in customers:
print(x["uid"], x["name"])
1 John
2 Smith
3 Andersson
## Modify an entry, This will change the name of customer 2 from Smith to Charlie
>>> customers[2]["name"]="charlie"
>>> print(customers)
[{'uid': 1, 'name': 'John'}, {'uid': 2, 'name': 'Smith'}, {'uid': 3, 'name': 'charlie'}]
## Add a new field to each entry
>>> for x in customers:
x["password"]="123456" # any initial value
>>> print(customers)
101
MRCET
PYTHON PROGRAMMING
III YEAR/II SEM
MRCET
[{'uid': 1, 'name': 'John', 'password': '123456'}, {'uid': 2, 'name': 'Smith', 'password':
'123456'}, {'uid': 3, 'name': 'charlie', 'password': '123456'}]
## Delete a field
>>> del customers[1]
>>> print(customers)
[{'uid': 1, 'name': 'John', 'password': '123456'}, {'uid': 3, 'name': 'charlie', 'password':
'123456'}]
>>> del customers[1]
>>> print(customers)
[{'uid': 1, 'name': 'John', 'password': '123456'}]
## Delete all fields
>>> for x in customers:
del x["uid"]
>>> x
{'name': 'John', 'password': '123456'}
Comprehension:
Dictionary comprehensions can be used to create dictionaries from arbitrary key and
value expressions:
>>> z={x: x**2 for x in (2,4,6)}
>>> z
{2: 4, 4: 16, 6: 36}
>>> dict11 = {x: x*x for x in range(6)}
>>> dict11
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
102
PYTHON PROGRAMMING
III YEAR/II SEM
MRCET
UNIT – V
FILES, EXCEPTIONS, MODULES, PACKAGES
Files and exception: text files, reading and writing files, command line arguments, errors
and exceptions, handling exceptions, modules (datetime, time, OS , calendar, math module),
Explore packages
...
Python gives
you easy ways to manipulate these files
...
Text files are simple text where as the binary files contain binary
data which is only readable by computer
...
Binary files: In this type of file, there is no terminator for a line and the data is stored
after converting it into machine understandable binary language
...
In general, when a Python script encounters a
situation that it cannot cope with, it raises an exception
...
Text files:
We can create the text files by using the syntax:
Variable name=open (“file
...
txt","w+")
We declared the variable f to open a file named hello
...
Open takes 2 arguments, the
file that we want to open and a string that represents the kinds of permission or
operation we want to do on the file
Here we used "w" letter in our argument, which indicates write and the plus sign that
means it will create a file if it does not exist in library
103
PYTHON PROGRAMMING
III YEAR/II SEM
MRCET
The available option beside "w" are "r" for read and "a" for append and plus sign
means if it is not there then create it
File Modes in Python:
Mode
Description
'r'
This is the default mode
...
'w'
This Mode Opens file for writing
...
If file exists it truncates the file
...
If file already exists, the operation fails
...
If file does not exist, it creates a new file
...
It opens in text mode
...
'+'
This will open a file for reading and writing (updating)
Reading and Writing files:
The following image shows how to create and open a text file in notepad from command
prompt
104
PYTHON PROGRAMMING
III YEAR/II SEM
(or)
Hit on enter then it shows the following whether to open or not?
Click on “yes” to open else “no” to cancel
# Write a python program to open and read a file
a=open(“one
...
read())
105
MRCET
PYTHON PROGRAMMING
III YEAR/II SEM
MRCET
a
...
py
welcome to python programming
(or)
Note: All the program files and text files need to saved together in a particular file then
only the program performs the operations in the given file mode
f
...
txt stored
# Write a python program to open and write “hello world” into a file?
f=open("1
...
write("hello world")
f
...
txt file is created automatically and adds hello world
into txt file
If we keep on executing the same program for more than one time then it append the data
that many times
# Write a python program to write the content “hi python programming” for the
existing file
...
txt",'w')
f
...
close()
Output:
In the above program the hello txt file consist of data like
107
PYTHON PROGRAMMING
III YEAR/II SEM
MRCET
But when we try to write some data on to the same file it overwrites and saves with the
current data (check output)
# Write a python program to open and write the content to file and read it
...
txt","w+")
fo
...
read())
fo
...
txt file automatically and writes the data into it
108
PYTHON PROGRAMMING
III YEAR/II SEM
MRCET
Command line arguments:
The command line arguments must be given whenever we want to give the input before the
start of the script, while on the other hand, raw_input() is used to get the input while the
python program / script is running
...
‘sys’ module :
Python sys module stores the command line arguments into a list, we can access it
using sys
...
This is very useful and simple way to read command line arguments as
String
...
argv is the list of commandline arguments passed to the Python program
...
modules
...
# Python code to demonstrate the use of 'sys' module for command line arguments
import sys
# command line arguments are stored in the form
# of list in sys
...
argv
print(argumentList)
# Print the name of file
print(sys
...
argv[1])
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/cmndlinarg
...
py']
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/cmndlinarg
...
argv))
print('The command line arguments are:')
for i in sys
...
py ==
The command line arguments are:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/symod
...
import sys
print("System version is:")
print(sys
...
version_info)
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/s1
...
8
...
8
...
1916 32 bit (Intel)]
Version Information is:
sys
...
Python getopt module is useful in parsing command line
arguments where we want user to enter some options too
...
ArgumentParser(description='Process some integers
...
ArgumentParser()
print(parser
...
It provides a
lot of option such as positional arguments, default value for arguments, help message,
specifying data type of argument etc
It parses the command line options and parameter list
...
getopt(args, shortopts, longopts=[ ])
args are the arguments to be passed
...
Optional parameter, longopts is the list of String parameters this function accepts
which should be supported
...
-h --------- print help and usage message
-m --------- accept custom option value
-d --------- run the script in debug mode
import getopt
import sys
argv = sys
...
getopt(argv, 'hm:d', ['help', 'my_file='])
#print(opts)
print(args)
except getopt
...
exit(2)
111
PYTHON PROGRAMMING
III YEAR/II SEM
MRCET
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/gtopt
...
py']
Errors and Exceptions:
Python Errors and Built-in Exceptions: Python (interpreter) raises exceptions when it
encounters errors
...
Error caused by not following the proper structure (syntax) of the language
is called syntax error or parsing error
ZeroDivisionError:
ZeroDivisionError in Python indicates that the second argument used in a division (or
modulo) operation was zero
...
This is typically due to excessively large float values, as integer
values that are too big will opt to raise memory errors instead
...
This may happen if you
made a typing mistake in the module name or the module doesn't exist in its standard path
...
IndexError:
An IndexError exception is raised when you refer a sequence which is out of range
...
TypeError:
When two unrelated type of objects are combined, TypeErrorexception is raised
...
112
PYTHON PROGRAMMING
III YEAR/II SEM
MRCET
IndentationError:
Unexpected indent
...
You are free to choose the
number of spaces of indentation to use, but you then need to stick with it
...
They arise when the Python parser is unable to
understand a line of code
...
e
...
Run-time error:
A run-time error happens when Python understands what you are saying, but runs into
trouble when following your instructions
...
is
requested
(using
the
Value Error:
In Python, a value is the information that is stored within a certain object
...
Python has many built-in exceptions which forces your program to output an error when
something in it goes wrong
...
This exception class has to be derived, either directly or indirectly,
from Exception class
...
ClassNotFoundException
...
IOException
...
NoSuchFieldException
...
For example, an incorrect
input, a malfunctioning IO device etc
...
Hence,
the exceptions should be properly handled so that an abrupt termination of the program is
prevented
...
Both keywords are followed by
indented blocks
...
),
At developer level and compile level it gives errors
...
e
...
,),
As a developer we test the application, during that time logical error may obtained
...
e
...
The things we need to observe are:
1
...
2
...
Ex: Banking Transaction
3
...
114
PYTHON PROGRAMMING
III YEAR/II SEM
MRCET
For ex:
a=5
b=2
print(a/b)
print("Bye")
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/ex1
...
5
Bye
The above is normal execution with no error, but if we say when b=0, it is a
critical and gives error, see below
a=5
b=0
print(a/b)
print("bye") #this has to be printed, but abnormal termination
Output:
Traceback (most recent call last):
File "C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/ex2
...
py
number can not be divided by zero
bye
The except block executes only when try block has an error, check it below
a=5
b=2
try:
print(a/b)
except Exception:
print("number can not be divided by zero")
print("bye")
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/ex4
...
5
For example if you want to print the message like what is an error in a program
then we use “e” which is the representation or object of an exception
...
py
number can not be divided by zero division by zero
bye
(Type of error)
Let us see some more examples:
I don’t want to print bye but I want to close the file whenever it is opened
...
py
resource opened
2
...
py
resource opened
number can not be divided by zero division by zero
Note: resource not closed
To overcome this, keep print(“resource closed”) in except block, see it
a=5
b=0
try:
print("resource opened")
print(a/b)
except Exception as e:
print("number can not be divided by zero",e)
print("resource closed")
Output:
118
PYTHON PROGRAMMING
III YEAR/II SEM
MRCET
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/ex8
...
e
...
py
resource opened
2
...
a=5
b=0
try:
119
PYTHON PROGRAMMING
III YEAR/II SEM
MRCET
print("resource open")
print(a/b)
k=int(input("enter a number"))
print(k)
except ZeroDivisionError as e:
print("the value can not be divided by zero",e)
finally:
print("resource closed")
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/ex10
...
py
resource open
2
...
py
resource open
2
...
py", line
7, in
k=int(input("enter a number"))
ValueError: invalid literal for int() with base 10: ' p'
120
PYTHON PROGRAMMING
III YEAR/II SEM
MRCET
#-------------------a=5
b=0
try:
print("resource open")
print(a/b)
k=int(input("enter a number"))
print(k)
except ZeroDivisionError as e:
print("the value can not be divided by zero",e)
except ValueError as e:
print("invalid input")
except Exception as e:
print("something went wrong
...
py
resource open
the value can not be divided by zero division by zero
resource closed
Change the value of b to 2 and give the input as some character or string (other
than int)
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/ex12
...
5
enter a number p
invalid input
resource closed
Modules (Date, Time, os, calendar, math):
• Modules refer to a file containing Python statements and definitions
...
Furthermore, modules provide reusability of code
...
• Modular programming refers to the process of breaking a large, unwieldy
programming task into separate, smaller, more manageable subtasks or modules
...
If you’re working on a single
module, you’ll have a smaller problem domain to wrap your head around
...
• Maintainability: Modules are typically designed so that they enforce logical
boundaries between different problem domains
...
This makes it more
viable for a team of many programmers to work collaboratively on a large application
...
This eliminates
the need to recreate duplicate code
...
• Functions, modules and packages are all constructs in Python that promote code
modularization
...
g
...
py, is called a module and its module name
would be example
...
The function takes
in two numbers and returns their sum
...
• We use the import keyword to do this
...
• Using the module name we can access the function using dot (
...
For Eg:
>>> import example
>>> example
...
Standard modules can be imported
the same way as we import our user-defined modules
...
py
8
>>> import add
8
123
PYTHON PROGRAMMING
III YEAR/II SEM
MRCET
>>> import add
>>> import add
>>>
Python provides a neat way of doing this
...
This is how its done
...
reload(my_module) This
code got executed
py'>how its done
...
reload(add)
8
...
For ex:
124
'__name__',
PYTHON PROGRAMMING
III YEAR/II SEM
>>> example
...
datetime(2019,5,27,6,35,40)
>>> a
datetime
...
date(2000,9,18)
print(a)
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/d1
...
time(5,3)
print(a)
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/d1
...
import datetime
125
MRCET
PYTHON PROGRAMMING
III YEAR/II SEM
MRCET
a=datetime
...
today()
b=datetime
...
now()
print(a)
print(b)
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/d1
...
235581
2019-11-29 12:49:52
...
import datetime
a=datetime
...
today()
b=datetime
...
py =
2019-12-06
#write a python program to print the no
...
date
...
date(2020,5,27)
c=b-a
print(c)
Output:
126
PYTHON PROGRAMMING
III YEAR/II SEM
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/d1
...
datetime
...
date())
print(t
...
py =
2019-11-29
12:53:39
...
import time
print(time
...
py =
1575012547
...
import time
print(time
...
time()))
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/t1
...
struct_time(tm_year=2019, tm_mon=11, tm_mday=29, tm_hour=13, tm_min=1,
tm_sec=15, tm_wday=4, tm_yday=333, tm_isdst=0)
#write a python program to make a time stamp
...
mktime(a))
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/t1
...
0
#write a python program using sleep()
...
sleep(6)
#prints after 6 seconds
print("Python Lab")
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/t1
...
name
'nt'
>>> os
...
mkdir("temp1")
128
PYTHON PROGRAMMING
III YEAR/II SEM
MRCET
Note: temp1 dir is created
>>> os
...
py","a")
<_io
...
py' mode='a' encoding='cp1252'>
>>> os
...
py",os
...
access("t1
...
W_OK)
True
>>> os
...
py","t3
...
access("t1
...
F_OK)
False
>>> os
...
py",os
...
rmdir('temp1')
(or)
os
...
remove("t3
...
access("t3
...
F_OK)
False
>>> os
...
py', 'ali
...
py', 'arr
...
py', 'arr3
...
py', 'arr5
...
py', 'br
...
py', 'bubb
...
py', 'bubb3
...
py', 'bubbdesc
...
py', 'cmndlinarg
...
py', 'con1
...
py', 'cont2
...
py', 'dic
...
py', 'example
...
y
...
py', 'fr
...
py', 'fr3
...
py', 'fu1
...
py', 'if2
...
py', 'ifelse
...
py', 'insertdesc
...
py', 'k1
...
py', 'l2
...
py', 'linklisttt
...
py',
'listlooop
...
py', 'merg
...
py', 'nestedif
...
py', 'paraarg
...
py', 'qukdesc
...
py', 'r
...
py', 'ret
...
py', 's1
...
py',
'selecasce
...
py', 'stk
...
py', 'strr
...
py', 'strr2
...
py',
'strr4
...
py', 'wh
...
py', 'wh2
...
py', 'wh4
...
py',
'__pycache__']
>>> os
...
py', 'br
...
py', 'cmndlinarg
...
py', 'f1
...
py', 'funturet
...
py', 'include', 'Lib', 'libs', 'LICENSE
...
py',
'mysite', 'NEWS
...
exe', 'python3
...
dll', 'pythonw
...
py', 'sy
...
py', 'tcl', 'the_weather', 'Tools', 'tupretval
...
dll']
Calendar module:
130
PYTHON PROGRAMMING
III YEAR/II SEM
MRCET
#write a python program to display a particular month of a year using calendar
module
...
month(2020,1))
Output:
# write a python program to check whether the given year is leap or not
...
isleap(2021))
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/cl1
...
import calendar
print(calendar
...
import math
r=int(input("Enter radius:"))
area=math
...
py =
Enter radius:4
Area of circle is: 50
...
pi)
O/P: The value of pi is 3
...
• For Eg:
>>> import math as m
>>> print("The value of pi is", m
...
141592653589793
• We have renamed the math module as m
...
• Note that the name math is not recognized in our scope
...
pi is
invalid, m
...
Python from
...
Here is an example
...
141592653589793
• We imported only the attribute pi from the module
...
We could have imported multiple attributes
as follows
...
141592653589793
>>> e
2
...
>>>from math import *
>>>print("The value of pi is", pi)
• We imported all the definitions from the math module
...
Explore packages:
• We don't usually store all of our files in our computer in the same location
...
• Similar files are kept in the same directory, for example, we may keep all the songs in
the "music" directory
...
• As our application program grows larger in size with a lot of modules, we place
similar modules in one package and different modules in different packages
...
• Similar, as a directory can contain sub-directories and files, a Python package can
have sub-packages and modules
...
py in order for Python to consider it as
a package
...
• Here is an example
...
134
PYTHON PROGRAMMING
III YEAR/II SEM
MRCET
• If a file named __init__
...
This can be used for execution of
package initialization code, such as initialization of package-level data
...
py
• A module in the package can access the global by importing it in turn
• We can import modules from packages using the dot (
...
• For example, if want to import the start module in the above example, it is done as
follows
...
Level
...
• Game
...
start
...
• from Game
...
• start
...
• from Game
...
start import select_difficulty
• Now we can directly call this function
...
CSE import student
>>> student
...
write()
Student
>>> from IIYEAR
...
student import read
>>> read
136
PYTHON PROGRAMMING
III YEAR/II SEM
MRCET
>>> read()
Department
>>> from IIYEAR
...
student import write
>>> write()
Student
# Write a program to create and import module?
def add(a=4,b=6):
c=a+b
return c
Output:
C:\Users\MRCET\AppData\Local\Programs\Python\Python38-32\IIYEAR\modu1
...
add()
10
# Write a program to create and rename the existing module
...
py
hello world
>>> import exam as ex
hello world
137
Title: Python programming
Description: Python programming notes typically documentation or written materials that explain and illustrate various concepts, syntax, and best practices related to the Python programming language. These notes can cover topics ranging from the basics of Python, such as data types, variables, and control structures, to more advanced topics like object-oriented programming, web development, data analysis, and machine learning using Python. Such notes often include code examples, explanations, and practical applications to help learners understand and implement Python code effectively. They may also contain tips, tricks, and common pitfalls to watch out for while programming in Python. These resources are often utilized by beginners and experienced developers alike to deepen their understanding of Python and improve their programming skills.
Description: Python programming notes typically documentation or written materials that explain and illustrate various concepts, syntax, and best practices related to the Python programming language. These notes can cover topics ranging from the basics of Python, such as data types, variables, and control structures, to more advanced topics like object-oriented programming, web development, data analysis, and machine learning using Python. Such notes often include code examples, explanations, and practical applications to help learners understand and implement Python code effectively. They may also contain tips, tricks, and common pitfalls to watch out for while programming in Python. These resources are often utilized by beginners and experienced developers alike to deepen their understanding of Python and improve their programming skills.