(R18A0513) Python Programming
(R18A0513) Python Programming
[R18A0513]
Maisammaguda, Dhulapally (Post Via. Hakimpet), Secunderabad – 500100, Telangana State, India
Python Programming
SYLLABUS
MALLA REDDY COLLEGE OF ENGINEERING AND TECHNOLOGY
UNIT I
INTRODUCTION DATA, EXPRESSIONS, STATEMENTS
Introduction to Python and installation, variables, expressions, statements, Numeric data types: Int, float,
Boolean, string. Basic data types: list--- list operations, list slices, list methods, list loop, mutability, aliasing,
cloning lists, list parameters. Tuple --- tuple assignment, tuple as return value, tuple methods. Sets: operations
and methods. Dictionaries: operations and methods.
UNIT II
CONTROL FLOW, LOOPS, FUNCTIONS
Conditionals: Boolean values and operators, conditional (if), alternative (if-else), chained conditional (if-
elif-else); Iteration: statements break, continue.Functions--- function and its use, pass keyword, flow of
execution, parameters and arguments.
UNIT III
ADVANCED FUNCTIONS, ARRAYS
Fruitful functions: return values, parameters, local and global scope, function composition,
recursion; Advanced Functions: lambda, map, filter, reduce, basic data type
comprehensions. Python arrays: create an array, Access the Elements of an Array, array
methods.
UNIT IV
FILES,EXCEPTIONS
File I/O, Exception Handling, introduction to basic standard libraries, Installation of pip,
Demonstrate Modules: Turtle, pandas, numpy, pdb, Explore packages.
UNIT V
OOPS,FRAMEWORK : Object,Class,Method,Inheritance, Polymorphism,Data Abstraction,
Encapsulation, Python Frameworks: Explore django framework with an example
Python Programming
OUTCOMES: Upon completion of the course, students will be able to
Read, write, execute by hand simple Python programs.
Structure simple Python programs for solving problems.
Decompose a Python program into functions.
Represent compound data using Python lists, tuples, dictionaries.
Read and write data from/to files in Python Programs
TEXT BOOKS
1. Allen B. Downey, ``Think Python: How to Think Like a Computer Scientist‗‗, 2nd edition,
Updated for Python 3, Shroff/O‗Reilly Publishers, 2016.
2. R. Nageswara Rao, ―Core Python Programming‖, dreamtech
3. Python Programming: A Modern Approach, Vamsi Kurama, Pearson
REFERENCE BOOKS:
1. Core Python Programming, W.Chun, Pearson.
2. Introduction to Python, Kenneth A. Lambert, Cengage
3. Learning Python, Mark Lutz, Orielly
Python Programming
INDEX
UNIT TOPIC PAGE NO
INTRODUCTION DATA, EXPRESSIONS,
STATEMENTS
Introduction to Python and installation 6-10
Variables 11-13
Expressions, Statements 14-18
Data types: Int, float, Boolean, string. 19-30
Basic data types: list--- list operations, list 31-38
slices, list methods,
I list loop, mutability, aliasing, cloning lists, list 39-47
parameters.
Tuple --- tuple assignment, tuple as return 48-50
value, tuple methods
Dictionaries: operations and methods. 51-56
CONTROL FLOW, LOOPS, FUNCTIONS
Conditionals: Boolean values and operators 57-59
Conditional (if), alternative (if-else), Chained 59-63
II conditional (if-elif-else)
Iterations 64-71
Statements break, continue. 72-77
Functions and its use 78-82
Pass keyword, flow of execution, parameters 83-92
and arguments.
ADVANCED FUNCTIONS,
ARRAYS
Fruitful functions: return values, parameters, 93-96
Local and Global scope, function 97-99
Composition
Recursion, lambda, map, filter, reduce, 100-101
III
Basic data type comprehensions 102-103
Python arrays: create an array, 103-106
Access the Elements of an Array,
array methods.
Python Programming
FILES,EXCEPTIONS ,
File I/O 107-115
Exception Handling 116-126
introduction to basic standard libraries 127-143
Installation of pip 144-145
Demonstrate Modules: Turtle 146-149
Pandas 150-153
Numpy 154-157
IV Pdb, Explore packages. 158-160
V OOPS,FRAMEWORK
Object,Class,Method 161-163
Inheritance 163-169
Polymorphism 170-171
Data Abstraction 171-173
Encapsulation 173-174
Python Frameworks 175-176
Explore django framework with an 177-183
example
Python Programming
III YEAR/I SEM
UNIT – I
INTRODUCTION DATA, EXPRESSIONS, STATEMENTS
Introduction to Python and installation, variables, expressions, statements, Numeric data types:
Int, float, Boolean, string. Basic data types: list--- list operations, list slices, list methods, list
loop, mutability, aliasing, cloning lists, list parameters. Tuple --- tuple assignment, tuple as
return value, tuple methods. Dictionaries: operations and methods.
Python is a widely used general-purpose, high level programming language. It was initially
designed by Guido van Rossum in 1991 and developed by Python Software Foundation. It
was mainly developed for emphasis on code readability, and its syntax allows programmers
to express concepts in fewer lines of code.
Python is a programming language that lets you work quickly and integrate systems more
efficiently.
There are two major Python versions- Python 2 and Python 3.
• On 16 October 2000, Python 2.0 was released with many new features.
• On 3rd December 2008, Python 3.0 was released with more testing and includes new
features.
# Script Begins
Statement3
# Script Ends
The following are the primary factors to use python in day-to-day life:
1. Python is object-oriented
Structure supports such concepts as polymorphism, operation overloading and
multiple inheritance.
2. Indentation:Indentation is one of the greatest feature in python
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.org/downloads/
Steps to be followed and remembered:
Step 1: Select Version of Python to Install.
Step 2: Download Python Executable Installer.
Step 3: Run Executable Installer.
Step 4: Verify Python Was Installed On Windows.
Step 5: Verify Pip Was Installed.
Python Programming Page | 8
III YEAR/I SEM
Step 6: Add Python Path to Environment Variables (Optional)
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). Your code is automatically
compiled, but then it is interpreted.
Source Byte code Runtime
PVM
m.py m.pyc
hello world
>>> x=[0,1,2]
>>> x
#If a quantity is stored in memory, typing its name will display it.
[0, 1, 2]
>>> 2+3
The chevron at the beginning of the 1st line, i.e., the symbol >>> is a prompt the python
interpreter uses to indicate that it is ready. If the programmer types 2+6, the interpreter
replies 8.
Alternatively, programmers can store Python script source code in a file with
the .py extension, and use the interpreter to execute the contents of the file. To execute the
script by the interpreter, you have to tell the interpreter the name of the file. For example, if
you have a script name MyFile.py and you're working on Unix, to run the script you have to
type:
python MyFile.py
Working with the interactive mode is better when Python programmers deal with small
pieces of code as you can type and execute them immediately, but when the code is more
than 2-4 lines, using the script for coding can help to modify and use the code in future.
Example:
Variables:
Variables are nothing but reserved memory locations to store values. This means that when
you create a variable you reserve some space in memory.
Based on the data type of a variable, the interpreter allocates memory and decides what can
be stored in the reserved memory. Therefore, by assigning different data types to variables,
you can store integers, decimals or characters in these variables.
• Variable names are case-sensitive (age, Age and AGE are three different variables)
Python variables do not need explicit declaration to reserve memory space. The declaration
happens automatically when you assign a value to a variable. The equal sign (=) is used to
assign values to variables.
The operand to the left of the = operator is the name of the variable and the operand to the
right of the = operator is the value stored in the variable.
For example −
c = "John" # A string
print (a)
print (b)
print (c)
1000.0
John
Multiple Assignment:
Python allows you to assign a single value to several variables simultaneously.
For example :
a=b=c=1
Here, an integer object is created with the value 1, and all three variables are assigned to the
same memory location. You can also assign multiple objects to multiple variables.
Python Programming Page | 12
III YEAR/I SEM
For example −
a,b,c = 1,2,"mrcet“
Here, two integer objects with values 1 and 2 are assigned to variables a and b respectively,
and one string object with the value "john" is assigned to the variable c.
Output Variables:
The Python print statement is often used to output variables.
Variables do not need to be declared with any particular type and can even change type after
they have been set.
x=5 # x is of type int
x = "mrcet " # x is now of type str
print(x)
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:
Python Programming Page | 13
III YEAR/I SEM
An expression is a combination of values, variables, and operators. An expression is
evaluated using assignment operator.
Examples: Y=x + 17
>>> x=10
>>> z=x+20
>>> z
30
>>> x=10
>>> y=20
>>> c=x+y
>>> c
30
>>> y=20
>>> y
20
Python also defines expressions only contain identifiers, literals, and operators. So,
Identifiers: Any name that is used to define a class, function, variable module, or object is
an identifier.
Literals: These are language-independent terms in Python and should exist independently in
any programming language. In Python, there are the string literals, byte literals, integer
literals, floating point literals, and imaginary literals.
Operators: In Python you can implement the following operations using the corresponding
tokens.
add +
subtract -
multiply *
Integer Division /
remainder %
and &
or \
Check equality ==
Generator expression:
Syntax: ( compute(var) for var in iterable )
>>> print(x)
<generator object <genexpr> at 0x033EEC30>
You might expect this to print as ('a', 'b', 'c') but it prints as <generator object <genexpr>
at 0x02AAD710> The result of a tuple comprehension is not a tuple: it is actually a
generator. The only thing that you need to know now about a generator now is that you
can iterate over it, but ONLY ONCE.
Conditional expression:
Syntax: true_value if Condition else false_value
>>> x
'1'
Statements:
A statement is an instruction that the Python interpreter can execute. We have normally two
basic statements, the assignment statement and the print statement. Some other kinds of
statements that are if statements, while statements, and for statements generally called as
control flows.
Examples:
An print statement is something which is an input from the user, to be printed / displayed on
to the screen (or ) monitor.
mrcet college
Precedence of Operators:
Operator precedence affects how an expression is evaluated.
For example, x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has higher
precedence than +, so it first multiplies 3*2 and then adds into 7.
Example 1:
>>> 3+4*2
11
>>> (10+10)*2
40
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)
17
PYTHON PROGRAMMING III YEAR/I SEM MRCET
e = (a + b) * (c / d); # (30) * (15/5)
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.py
Value of (a + b) * c / d is 90.0
Value of ((a + b) * c) / d is 90.0
Value of (a + b) * (c / d) is 90.0
Value of a + (b * c) / d is 50.0
Comments:
Single-line comments begins with a hash(#) symbol and is useful in mentioning that the
whole line should be considered as a comment until the end of line.
A Multi line comment is useful when we need to comment on many lines. In python, triple
double quote(“ “ “) and single quote(„ „ „)are used for multi-line commenting.
Example:
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/comm.py
30
18
PYTHON PROGRAMMING III YEAR/I SEM MRCET
Int:
>>> print(24656354687654+2)
24656354687656
>>> print(20)
20
>>> print(0b10)
2
19
PYTHON PROGRAMMING III YEAR/I 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)
<class 'int'>
>>> a=11
>>> print(type(a))
<class 'int'>
Float:
Float, or "floating point number" is a number, positive or negative, containing one or more
decimals.
Float can also be scientific numbers with an "e" to indicate the power of 10.
>>> y=2.8
>>> y
2.8
>>> y=2.8
>>> print(type(y))
<class 'float'>
>>> type(.4)
<class 'float'>
>>> 2.
20
PYTHON PROGRAMMING III YEAR/I SEM MRCET
2.0
Example:
x = 35e3
y = 12E4
z = -87.7e100
print(type(x))
print(type(y))
print(type(z))
Output:
<class 'float'>
<class 'float'>
<class 'float'>
Boolean:
Objects of Boolean type may have one of two values, True or False:
>>> type(True)
<class 'bool'>
>>> type(False)
<class 'bool'>
Strings:
A string is a group/ a sequence of characters. Since Python has no provision for arrays,
we simply use strings. This is how we declare a string. We can use a pair of single or
double quotes. Every string object is of the type „str‟.
>>> type("name")
<class 'str'>
>>> name=str()
>>> name
''
>>> a=str('mrcet')
>>> a
'mrcet'
>>> a=str(mrcet)
>>> a[2]
'c'
21
PYTHON PROGRAMMING III YEAR/I SEM MRCET
>>> letter = fruit[1]
The second statement selects character number 1 from fruit and assigns it to letter. The
expression in brackets is called an index. The index indicates which character in the
sequence we want
String slices:
A segment of a string is called a slice. 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.
Slicing will start from index and will go up to stop in step of steps.
Default value of start is 0,
Stop is last index of list
And for step default is 1
For example 1−
str = 'Hello World!'
Output:
Hello World!
llo
22
PYTHON PROGRAMMING III YEAR/I SEM MRCET
llo World!
Hello World!TEST
Example 2:
>>> x='computer'
>>> x[1:4]
'omp'
>>> x[1:6:2]
'opt'
>>> x[3:]
'puter'
>>> x[:5]
'compu'
>>> x[-1]
'r'
>>> x[-3:]
'ter'
>>> x[:-2]
'comput'
>>> x[::-2]
'rtpo'
>>> x[::-1]
'retupmoc'
23
PYTHON PROGRAMMING III YEAR/I SEM MRCET
Immutability:
It is tempting to use the [] operator on the left side of an assignment, with the intention of
changing a character in a string.
For example:
The reason for the error is that strings are immutable, which means we can‟t change an
existing string. The best we can do is creating a new string that is a variation on the original:
Note: The plus (+) sign is the string concatenation operator and the asterisk (*) is the
repetition operator
24
PYTHON PROGRAMMING III YEAR/I SEM MRCET
Note:
All the string methods will be returning either true or false as the result
1. isalnum():
25
PYTHON PROGRAMMING III YEAR/I SEM MRCET
Isalnum() method returns true if string has at least 1 character and all characters are
alphanumeric and false otherwise.
Syntax:
String.isalnum()
Example:
>>> string="123alpha"
>>> string.isalnum() True
2. isalpha():
isalpha() method returns true if string has at least 1 character and all characters are
alphabetic and false otherwise.
Syntax:
String.isalpha()
Example:
>>> string="nikhil"
>>> string.isalpha()
True
3. isdigit():
isdigit() returns true if string contains only digits and false otherwise.
Syntax:
String.isdigit()
Example:
>>> string="123456789"
>>> string.isdigit()
True
4. islower():
Islower() returns true if string has characters that are in lowercase and false otherwise.
Syntax:
26
PYTHON PROGRAMMING III YEAR/I SEM MRCET
String.islower()
Example:
>>> string="nikhil"
>>> string.islower()
True
5. isnumeric():
isnumeric() method returns true if a string contains only numeric characters and false
otherwise.
Syntax:
String.isnumeric()
Example:
>>> string="123456789"
>>> string.isnumeric()
True
6. isspace():
isspace() returns true if string contains only whitespace characters and false otherwise.
Syntax:
String.isspace()
Example:
>>> string=" "
>>> string.isspace()
True
7. istitle()
istitle() method returns true if string is properly “titlecased”(starting letter of each word is
capital) and false otherwise
Syntax:
String.istitle()
27
PYTHON PROGRAMMING III YEAR/I SEM MRCET
Example:
>>> string="Nikhil Is Learning"
>>> string.istitle()
True
8. isupper()
isupper() returns true if string has characters that are in uppercase and false otherwise.
Syntax:
String.isupper()
Example:
>>> string="HELLO"
>>> string.isupper()
True
9. replace()
replace() method replaces all occurrences of old in string with new or at most max
occurrences if max given.
Syntax:
String.replace()
Example:
>>> string="Nikhil Is Learning"
>>> string.replace('Nikhil','Neha')
'Neha Is Learning'
10. split()
split() method splits the string according to delimiter str (space if not provided)
Syntax:
String.split()
Example:
>>> string="Nikhil Is Learning"
>>> string.split()
28
PYTHON PROGRAMMING III YEAR/I SEM MRCET
['Nikhil', 'Is', 'Learning']
11. count()
count() method counts the occurrence of a string in another string Syntax:
String.count()
Example:
>>> string='Nikhil Is Learning'
>>> string.count('i')
3
12. find()
Find() method is used for finding the index of the first occurrence of a string in another
string
Syntax:
String.find(„string‟)
Example:
>>> string="Nikhil Is Learning"
>>> string.find('k')
2
13. swapcase()
converts lowercase letters in a string to uppercase and viceversa
Syntax:
String.find(„string‟)
Example:
>>> string="HELLO"
>>> string.swapcase()
'hello'
14. startswith()
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.
29
PYTHON PROGRAMMING III YEAR/I SEM MRCET
Syntax:
String.startswith(„string‟)
Example:
>>> string="Nikhil Is Learning"
>>> string.startswith('N')
True
15. endswith()
Determines if string or a substring of string (if starting index beg and ending index end are
given) ends with substring str; returns true if so and false otherwise.
Syntax:
String.endswith(„string‟)
Example:
>>> string="Nikhil Is Learning"
>>> string.startswith('g')
True
String module:
This module contains a number of functions to process standard Python strings. In recent
versions, most functions are available as string methods as well.
It‟s a built-in module and we have to import it before using any of its constants and classes
Note:
help(string) --- gives the information about all the variables ,functions, attributes and classes
to be used in string module.
Example:
import string
print(string.ascii_letters)
print(string.ascii_lowercase)
print(string.ascii_uppercase)
print(string.digits)
30
PYTHON PROGRAMMING III YEAR/I SEM MRCET
print(string.hexdigits)
#print(string.whitespace)
print(string.punctuation)
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/strrmodl.py
=========================================
abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
abcdefghijklmnopqrstuvwxyz
ABCDEFGHIJKLMNOPQRSTUVWXYZ
0123456789
0123456789abcdefABCDEF
!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~
Formatter
It behaves exactly same as str.format() function. This class becomes useful if you want to
subclass it and define your own format string syntax.
Template
This class is used to create a string template for simpler string substitutions
31
PYTHON PROGRAMMING III YEAR/I SEM MRCET
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]
32
PYTHON PROGRAMMING III YEAR/I SEM MRCET
List operations:
These operations include indexing, slicing, adding, multiplying, and checking for
membership
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.
Because lists are sequences, indexing and slicing work the same way for lists as they do for
strings.
Assuming following input −
L = ['mrcet', 'college', 'MRCET!']
33
PYTHON PROGRAMMING III YEAR/I SEM MRCET
L[-2] college Negative: count from the right
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. Here are all of the methods of list objects:
Del()
34
PYTHON PROGRAMMING III YEAR/I SEM MRCET
Append()
Extend()
Insert()
Pop()
Remove()
Reverse()
Sort()
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]
>>> del(x)
>>> x # complete list gets deleted
Append: Append an item to a list
>>> x=[1,5,8,4]
>>> x.append(10)
>>> x
[1, 5, 8, 4, 10]
Extend: Append a sequence to a list.
>>> x=[1,2,3,4]
>>> y=[3,6,9,1]
>>> x.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]
35
PYTHON PROGRAMMING III YEAR/I SEM MRCET
>>> x.insert(2,10) #insert(index no, item to be inserted)
>>> x
[1, 2, 10, 4, 6, 7]
>>> x.insert(4,['a',11])
>>> x
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.
>>> x.pop()
>>> x
[1, 2, 10, 4, 6]
>>> x.pop(2)
10
>>> x
[1, 2, 4, 6]
Remove: The remove() method removes the specified item from a given list.
>>> x=[1,33,2,10,4,6]
>>> x.remove(33)
>>> x
36
PYTHON PROGRAMMING III YEAR/I SEM MRCET
[1, 2, 10, 4, 6]
>>> x.remove(4)
>>> x
[1, 2, 10, 6]
>>> x.sort()
>>> x
[1, 2, 3, 4, 5, 6, 7]
>>> x=[10,1,5,3,8,7]
>>> 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.
list = ['M','R','C','E','T']
37
PYTHON PROGRAMMING III YEAR/I SEM MRCET
i=1
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/listlooop.py
1
3
5
7
9
Method #3: using while loop
Mutability:
A mutable object can be changed after it is created, and an immutable object can't.
>>> x=[1,2,4,6,7]
39
PYTHON PROGRAMMING III YEAR/I SEM MRCET
>>> x
[1, 2, 10, 4, 6, 7]
>>> x.insert(4,['a',11])
>>> x
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.
>>> x.pop()
>>> x
[1, 2, 10, 4, 6]
>>> x.pop(2)
10
>>> x
[1, 2, 4, 6]
Remove: The remove() method removes the specified item from a given list.
>>> x=[1,33,2,10,4,6]
>>> x.remove(33)
>>> x
[1, 2, 10, 4, 6]
40
PYTHON PROGRAMMING III YEAR/I SEM MRCET
>>> x.remove(4)
>>> x
[1, 2, 10, 6]
>>> x.sort()
>>> x
[1, 2, 3, 4, 5, 6, 7]
>>> x=[10,1,5,3,8,7]
>>> x.sort()
>>> x
[1, 3, 5, 7, 8, 10]
Aliasing:
1. An alias is a second name for a piece of data, often easier (and more useful) than
making a copy.
2. If the data is immutable, aliases don‟t matter because the data can‟t change.
3. But if data can change, aliases can result in lot of hard – to – find bugs.
4. Aliasing happens whenever one variable‟s value is assigned to another variable.
For ex:
a = [81, 82, 83]
41
PYTHON PROGRAMMING III YEAR/I 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.py
True
False
True
True
[5, 82, 83]
Because the same list has two different names, a and b, we say that it is aliased. Changes
made with one alias affect the other. In the example above, you can see that a and b refer to
the same list after executing the assignment statement b = a.
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. This process is sometimes called cloning, to
avoid the ambiguity of the word copy.
The easiest way to clone a list is to use the slice operator. Taking any slice of a creates a new
list. In this case the slice happens to consist of the whole list.
Example:
a = [81, 82, 83]
print(a == b)
print(a is b)
b[0] = 5
print(a)
print(b)
42
PYTHON PROGRAMMING III YEAR/I SEM MRCET
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/clo.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.
Since lists are mutable, changes made to the elements referenced by the parameter change
the same list that the argument is referencing.
# 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. """
List[position] = 2 * List[position]
things = [2, 5, 9]
print(things)
doubleStuff(things)
print(things)
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/lipar.py ==
[2, 5, 9]
43
PYTHON PROGRAMMING III YEAR/I SEM MRCET
List comprehension:
List:
List comprehensions provide a concise way to create lists. Common applications are to make
new lists where each element is the result of some operations applied to each member of
another sequence or iterable, or to create a subsequence of those elements that satisfy a
certain condition.
>>> list1=[]
list1.append(x**2)
>>> list1
(or)
>>> list1
(or)
>>> list1
>>> 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. In Python tuples are written
with round brackets.
Supports all operations for sequences.
Immutable, but member objects may be mutable.
If the contents of a list shouldn‟t change, use a tuple to prevent items from
45
PYTHON PROGRAMMING III YEAR/I SEM MRCET
accidently being added, changed, or deleted.
Tuples are more efficient than list due to python‟s implementation.
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)
46
PYTHON PROGRAMMING III YEAR/I 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. Tuples
are unchangeable.
>>> x=(2,5,7,'4',8)
>>> x[1]=10
Traceback (most recent call last):
File "<pyshell#41>", line 1, in <module>
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.count(2)
4
Index (): Searches the tuple for a specified value and returns the position of where it
was found
47
PYTHON PROGRAMMING III YEAR/I SEM MRCET
>>> 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.index(2)
>>> print(y)
1
Length (): To know the number of items or values present in a tuple, we use len().
>>> 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. In here, we have assigned tuple 1 with the college information like college name, year,
etc. and another tuple 2 with the values in it like number (1, 2, 3… 7).
For Example,
>>> print(tup1[0])
mrcet
>>> print(tup2[1:4])
(2, 3, 4)
48
PYTHON PROGRAMMING III YEAR/I SEM MRCET
We call the value for [0] in tuple and for tuple 2 we call the value between 1 and 4
Run the above code- It gives name mrcet for first tuple while for second tuple it gives
number (2, 3, 4)
A Tuple is a comma separated sequence of items. It is created with or without (). Tuples are
immutable.
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/tupretval.py
mrcet college
20
49
PYTHON PROGRAMMING III YEAR/I SEM MRCET
def f(x):
y0 = x + 1
y1 = x * 3
y2 = y0 ** y3
return (y0, y1, y2)
Tuple comprehension:
Tuple Comprehensions are special: The result of a tuple comprehension is special. You
might expect it to produce a tuple, but what it does is produce a special "generator"
object that we can iterate over.
For example:
>>> x = (i for i in 'abc') #tuple comprehension
>>> x
<generator object <genexpr> at 0x033EEC30>
>>> print(x)
<generator object <genexpr> at 0x033EEC30>
You might expect this to print as ('a', 'b', 'c') but it prints as <generator object <genexpr>
at 0x02AAD710> The result of a tuple comprehension is not a tuple: it is actually a
generator. The only thing that you need to know now about a generator now is that you
can iterate over it, but ONLY ONCE.
So, given the code
a
b
c
Create a list of 2-tuples like (number, square):
>>> z=[(x, x**2) for x in range(6)]
>>> z
[(0, 0), (1, 1), (2, 4), (3, 9), (4, 16), (5, 25)]
50
PYTHON PROGRAMMING III YEAR/I SEM MRCET
Set:
Similarly to list comprehensions, set comprehensions are also supported:
Dictionaries:
Example:
>>> dict1 = {"brand":"mrcet","model":"college","year":2004}
>>> dict1
{'brand': 'mrcet', 'model': 'college', 'year': 2004}
Methods that are available with dictionary are tabulated below. Some of them have already
been used in the above examples.
Method Description
51
PYTHON PROGRAMMING III YEAR/I SEM MRCET
copy() Return a shallow copy of the dictionary.
52
PYTHON PROGRAMMING III YEAR/I SEM MRCET
To access specific value of a dictionary, we must pass its key,
>>> dict1 = {"brand":"mrcet","model":"college","year":2004}
>>> x=dict1["brand"]
>>> x
'mrcet'
mrcet
college
2004
brand
model
year
('brand', 'mrcet')
('model', 'college')
('year', 2004)
53
PYTHON PROGRAMMING III YEAR/I SEM MRCET
Remove
Length
Delete
Add/change values: You can change the value of a specific item by referring to its key
name
>>>{1: 1, 2: 4, 3: 9, 4: 16}
{1: 1, 2: 4, 3: 9, 4: 16}
>>> y=len(x)
>>> y
4
Iterating over (key, value) pairs:
>>> x = {1:1, 2:4, 3:9, 4:16, 5:25}
>>> for key in x:
print(key, x[key])
11
24
39
54
PYTHON PROGRAMMING III YEAR/I SEM MRCET
4 16
5 25
>>> for k,v in x.items():
print(k,v)
11
24
39
4 16
5 25
List of Dictionaries:
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'}]
>>> print(customers)
55
PYTHON PROGRAMMING III YEAR/I 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'}]
>>> x
{'name': 'John', 'password': '123456'}
Comprehension:
Dictionary comprehensions can be used to create dictionaries from arbitrary key and
value expressions:
56
PYTHON PROGRAMMING III YEAR/I SEM MRCET
UNIT – II
>>> 5 == 5
True
>>> 5 == 6
False
True and False are special values that belong to the type bool; they are not strings:
>>> type(True)
<class 'bool'>
>>> type(False)
<class 'bool'>
The == operator is one of the relational operators; the others are: x != y # x is not equal to y
Note:
57
PYTHON PROGRAMMING III YEAR/I SEM MRCET
All expressions involving relational and logical operators will evaluate to either true or false
Conditional (if):
The if statement contains a logical expression using which data is compared and a decision
is made based on the result of the comparison.
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 boolean expression evaluates to FALSE, then the first set of
code after the end of the if statement(s) is executed.
if Statement Flowchart:
a=3
if a > 2:
print(a, "is greater")
print("done")
a = -1
if a < 0:
print(a, "a is smaller")
print("Finish")
58
PYTHON PROGRAMMING III YEAR/I SEM MRCET
Output:
59
PYTHON PROGRAMMING III YEAR/I SEM MRCET
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/if1.py
3 is greater
done
-1 a is smaller
Finish
a=10
if a>9:
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/if2.py
A is Greater than 9
Alternative if (If-Else):
An else statement can be combined with an if statement. An else statement contains the
block of code (false block) that executes if the conditional expression in the if statement
resolves to 0 or a FALSE value.
The else statement is an optional statement and there could be at most only one else
Statement following if.
Syntax of if - else :
if test expression:
Body of if stmts
else:
Body of else stmts
If - else Flowchart :
60
PYTHON PROGRAMMING III YEAR/I SEM MRCET
Example of if - else:
a=int(input('enter the number'))
if a>5:
print("a is greater")
else:
print("a is smaller than the input given")
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/ifelse.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.py
B is Greater than A
61
PYTHON PROGRAMMING III YEAR/I SEM MRCET
The elif statement allows us to check multiple expressions for TRUE and execute a
block of code as soon as one of the conditions evaluates to TRUE. Similar to the else,
the elif statement is optional. However, unlike else, for which there can be at most one
statement, there can be an arbitrary number of elif statements following an if.
If test expression:
Body of if stmts
elif test expression:
Body of elif stmts
else:
Body of else stmts
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/ifelse.py
enter the number5
enter the number2
enter the number9
a is greater
>>>
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.py
100
Good bye!
63
PYTHON PROGRAMMING III YEAR/I SEM MRCET
Iteration:
A loop statement allows us to execute a statement or group of statements multiple times as
long as the condition is true. Repeated execution of a set of statements with the help of loops
is called iteration.
Loops statements are used when we need to run same code again and again, each time with a
different value.
Statements:
In Python Iteration (Loops) statements are of three types:
1. While Loop
2. For Loop
3. Nested For Loops
While loop:
Loops are either infinite or conditional. Python while loop keeps reiterating a block of
code defined inside it until the desired condition is met.
The while loop contains a boolean expression and the code inside the loop is
repeatedly executed as long as the boolean expression is true.
The statements that are executed inside while can be a single line of code or a block of
multiple statements.
Syntax:
while(expression):
Statement(s)
Flowchart:
64
PYTHON PROGRAMMING III YEAR/I SEM MRCET
Example Programs:
1.
i=1
while i<=6:
print("Mrcet college")
i=i+1
output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/wh1.py
Mrcet college
Mrcet college
Mrcet college
Mrcet college
Mrcet college
Mrcet college
2.
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.py
3.
i=1
65
PYTHON PROGRAMMING III YEAR/I SEM MRCET
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.py
4.
i=1
while (i < 10):
print (i)
i = i+1
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/wh4.py
1
2
3
4
5
6
7
8
9
2.
a=1
b=1
while (a<10):
print ('Iteration',a)
a=a+1
b=b+1
66
PYTHON PROGRAMMING III YEAR/I SEM MRCET
if (b == 4):
break
print ('While loop terminated')
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/wh5.py
Iteration 1
Iteration 2
Iteration 3
While loop terminated
count = 0
while (count < 9):
print("The count is:", count)
count = count + 1
print("Good bye!")
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/wh.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. It iterates over the items of lists, tuples, strings, the dictionaries and other
iterable objects
67
PYTHON PROGRAMMING III YEAR/I SEM MRCET
Sample Program:
numbers = [1, 2, 4, 6, 11, 20]
seq=0
for val in numbers:
seq=val*val
print(seq)
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/fr.py
1
4
16
36
121
400
Flowchart:
68
PYTHON PROGRAMMING III YEAR/I SEM MRCET
Iterating over a list:
#list of items
list = ['M','R','C','E','T']
i=1
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/lis.py
college 1 is M
college 2 is R
college 3 is C
college 4 is E
college 5 is T
tuple = (2,3,5,7)
print ('These are the first four prime numbers ')
#Iterating over the tuple
for a in tuple:
print (a)
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/fr3.py
These are the first four prime numbers
2
3
5
7
#creating a dictionary
college = {"ces":"block1","it":"block2","ece":"block3"}
69
PYTHON PROGRAMMING III YEAR/I SEM MRCET
for keys in college:
print (keys)
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/dic.py
Keys are:
ces
it
ece
Values are:
block1
block2
block3
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/strr.py
M
R
C
E
T
for j in range(5,i-1,-1):
print('')
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/nesforr.py
Output:
11111
2222
333
44
71
PYTHON PROGRAMMING III YEAR/I SEM MRCET
Break and continue:
In Python, break and continue statements can alter the flow of a normal loop. Sometimes
we wish to terminate the current iteration or even the whole loop without checking test
expression. The break and continue statements are used in these cases.
Break:
The break statement terminates the loop containing it and control of the program flows to
the statement immediately after the body of the loop. If break statement is inside a nested
loop (loop inside another loop), break will terminate the innermost loop.
Flowchart:
The following shows the working of break statement in for and while loop:
72
PYTHON PROGRAMMING III YEAR/I SEM MRCET
while test expression
# code inside while loop
If condition:
break (if break condition satisfies it jumps to outside loop)
# code inside while loop
# code outside while loop
Example:
print("The end")
Output:
M
R
C
E
T
The end
Output:
11
9
88
The number 88 is found
73
PYTHON PROGRAMMING III YEAR/I SEM MRCET
Terminating the loop
#
for letter in "Python": # First Example
if letter == "h":
break
print("Current Letter :", letter )
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/br.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. Loop does not terminate but continues on with the next iteration.
Flowchart:
The following shows the working of break statement in for and while loop:
74
PYTHON PROGRAMMING III YEAR/I SEM MRCET
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
Example:
# Program to show the use of continue statement inside loops
print("The end")
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/cont.py
s
t
r
n
g
The end
75
PYTHON PROGRAMMING III YEAR/I SEM MRCET
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/cont2.py
11
9
89
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/con1.py
Current Letter : P
Current Letter : y
Current Letter : t
Current Letter : o
Current Letter : n
Pass:
Example:
sequence = {'p', 'a', 's', 's'}
for val in sequence:
pass
76
PYTHON PROGRAMMING III YEAR/I SEM MRCET
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/f1.y.py
>>>
def f(arg): pass # a function that does nothing (yet) class C: pass # a class with
no
77
PYTHON PROGRAMMING III YEAR/I SEM MRCET
Functions:
Functions and its use: Function is a group of related statements that perform a specific task.
Functions help break our program into smaller and modular chunks. As our program grows
larger and larger, functions make it more organized and manageable. It avoids repetition and
makes code reusable.
integer = -20
Output:
def add_numbers(x,y):
sum = x + y
return sum
Output:
The sum is 25
Flow of Execution:
1. The order in which statements are executed is called the flow of execution
2. Execution always begins at the first statement of the program.
3. Statements are executed one at a time, in order, from top to bottom.
4. Function definitions do not alter the flow of execution of the program, but remember
that statements inside the function are not executed until the function is called.
5. Function calls are like a bypass in the flow of execution. 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.
78
PYTHON PROGRAMMING III YEAR/I SEM MRCET
Note: When you read a program, don‟t read from top to bottom. Instead, follow the flow of
execution. This means that you will read the def statements as you are scanning from top to
bottom, but you should skip the statements of the function definition until you reach a point
where that function is called.
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
welcome
0
1
2
Good morning college
The flow/order of execution is: 2,3,4,3,4,3,4,5
79
PYTHON PROGRAMMING III YEAR/I SEM MRCET
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 are passed during the definition of function while Arguments are passed during
the function call.
Example:
#here a and b are parameters
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/paraarg.py
25
There are three types of Python function arguments using which we can call a function.
1. Default Arguments
2. Keyword Arguments
3. Variable-length Arguments
Syntax:
def functionname():
80
PYTHON PROGRAMMING III YEAR/I SEM MRCET
statements
.
.
.
functionname()
Example:
def hf():
hello world
hf()
In the above example we are just trying to execute the program by calling the function. So it
will not display any error and no output on to the screen but gets executed.
print("hello world")
hf()
Output:
hello world
81
PYTHON PROGRAMMING III YEAR/I SEM MRCET
def hf():
print("hw")
hf()
hf()
hf()
Output:
hw
gh kfjg 66666
hw
gh kfjg 66666
hw
gh kfjg 66666
def add(x,y):
c=x+y
print(c)
add(5,4)
Output:
9
def add(x,y):
c=x+y
return c
print(add(5,4))
Output:
82
PYTHON PROGRAMMING III YEAR/I SEM MRCET
def add_sub(x,y):
c=x+y
d=x-y
return c,d
print(add_sub(10,5))
Output:
(15, 5)
The return statement is used to exit a function and go back to the place from where it was
called. This statement can contain expression which gets evaluated and the value is returned.
If there is no expression in the statement or the return statement itself is not present inside a
function, then the function will return the None object.
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.py
>>>
83
PYTHON PROGRAMMING III YEAR/I SEM MRCET
def hello_f():
return "hellocollege"
print(hello_f().upper())
Output:
HELLOCOLLEGE
# Passing Arguments
def hello(wish):
return '{}'.format(wish)
print(hello("mrcet"))
Output:
mrcet
Here, the function wish() has two parameters. Since, we have called this function with two
arguments, it runs smoothly and we do not get any error. If we call it with different number
of arguments, the interpreter will give errors.
def wish(name,msg):
wish("MRCET","Good morning!")
Output:
Hello MRCET Good morning!
84
PYTHON PROGRAMMING III YEAR/I SEM MRCET
Below is a call to this function with one and no arguments along with their respective error
messages.
>>> wish("MRCET") # only one argument
TypeError: wish() missing 1 required positional argument: 'msg'
>>> wish() # no arguments
TypeError: wish() missing 2 required positional arguments: 'name' and 'msg'
def hello(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.
Python allows functions to be called using keyword arguments. When we call functions in
this way, the order (position) of the arguments can be changed.
(Or)
If you have some functions with many parameters and you want to specify only some
of them, then you can give values for such parameters by naming them - this is
called keyword arguments - we use the name (keyword) instead of the position
(which we have been using all along) to specify the arguments to the function.
There are two advantages - one, using the function is easier since we do not need to
worry about the order of the arguments. Two, we can give values to only those
parameters which we want, provided that the other parameters have default argument
values.
85
PYTHON PROGRAMMING III YEAR/I 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 first usage, func(3, 7), the parameter a gets the value 3, the parameter b gets the
value 5 and c gets the default value of 10.
In the second usage func(25, c=24), the variable a gets the value of 25 due to the
position of the argument. Then, the parameter c gets the value of 24 due to naming i.e.
keyword arguments. The variable b gets the default value of 5.
def func(b=5, c=10,a): # shows error : non-default argument follows default argument
86
PYTHON PROGRAMMING III YEAR/I SEM MRCET
Output:
B and A are friends
#Default Arguments
Function arguments can have default values in Python.
We can provide a default value to an argument by using the assignment operator (=)
def hello(wish,name='you'):
return '{},{}'.format(wish,name)
print(hello("good morning"))
Output:
good morning,you
def hello(wish,name='you'):
Output:
Note: Any number of arguments in a function can have a default value. But once we have a
default argument, all the arguments to its right must also have default values.
This means to say, non-default arguments cannot follow default arguments. For example, if
we had defined the function header above as:
87
PYTHON PROGRAMMING III YEAR/I SEM MRCET
""" This function will print sum of two numbers
print (a+b)
Output:
Variable-length arguments
Sometimes you may need more arguments to process function then you mentioned in the
definition. If we don‟t know in advance about the arguments needed in function, we can use
variable-length arguments also called arbitrary arguments.
For this an asterisk (*) is placed before a parameter in function definition which can hold
non-keyworded variable-length arguments and a double asterisk (**) is placed before a
parameter in function which can hold keyworded variable-length 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‟.
def wish(*names):
"""This function greets all
the person in the names tuple."""
wish("MRCET","CSE","SIR","MADAM")
88
PYTHON PROGRAMMING III YEAR/I 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.
pi=3.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.py
Enter radius of circle 3
28.259999999999998
#Program to write sum different product and using arguments with return value
function.
def calculete(a,b):
total=a+b
diff=a-b
prod=a*b
div=a/b
mod=a%b
89
PYTHON PROGRAMMING III YEAR/I SEM MRCET
return total,diff,prod,div,mod
a=int(input("Enter a value"))
b=int(input("Enter b value"))
#function call
s,d,p,q,m = calculete(a,b)
#print("diff= ",d)
#print("mul= ",p)
#print("div= ",q)
#print("mod= ",m)
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/fu1.py
Enter a value 5
Enter b value 6
Sum= 11 diff= -1 mul= 30 div= 0.8333333333333334 mod= 5
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:
90
PYTHON PROGRAMMING III YEAR/I SEM MRCET
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/fu1.py
Enter a value 5
Enter b value-2
big number= 5
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.py
Enter a value 5
Enter b value -6
Enter c value 7
big number= 7
#Writer a program to read one subject mark and print pass or fail use single return
values function with argument.
def result(a):
if a>40:
return "pass"
91
PYTHON PROGRAMMING III YEAR/I 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.py
Enter one subject marks 35
fail
#Write a program to display mrecet cse dept 10 times on the screen. (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.py
mrcet cse dept 0
mrcet cse dept 1
mrcet cse dept 2
mrcet cse dept 3
mrcet cse dept 4
mrcet cse dept 5
mrcet cse dept 6
mrcet cse dept 7
mrcet cse dept 8
mrcet cse dept 9
92
PYTHON PROGRAMMING III YEAR/I SEM MRCET
UNIT – III
ADVANCED FUNCTIONS, ARRAYS
Fruitful functions: return values, parameters, local and global scope, function composition,
recursion; Advanced Functions: lambda, map, filter, reduce, basic data type comprehensions.
Python arrays: create an array, Access the Elements of an Array, array methods.
Functions, Arrays:
Fruitful functions:
We write functions that return values, which we will call fruitful functions. We have seen
the return statement before, but in a fruitful function the return statement includes a return
value. This statement means: "Return immediately from this function and use the following
expression as a return value."
(or)
Any function that returns a value is called Fruitful function. A Function that does not return
a value is called a void function
Return values:
The Keyword return is used to return back the value to the called function.
def area(radius):
temp = 3.14 * radius**2
return temp
print(area(4))
(or)
def area(radius):
return 3.14 * radius**2
print(area(2))
def absolute_value(x):
93
PYTHON PROGRAMMING III YEAR/I SEM MRCET
if x < 0:
return -x
else:
return x
Since these return statements are in an alternative conditional, only one will be executed.
As soon as a return statement executes, the function terminates without executing any
subsequent statements. Code that appears after a return statement, or any other place the
flow of execution can never reach, is called dead code.
In a fruitful function, it is a good idea to ensure that every possible path through the program
hits a return statement. 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. If the flow of execution gets to the end of a
function, the return value is None, which is not the absolute value of 0.
By the way, Python provides a built-in function called abs that computes absolute values.
# Write a Python function that takes two lists and returns True if they have at least one
common member.
Output:
94
PYTHON PROGRAMMING III YEAR/I SEM MRCET
C:\Users\MRCET\AppData\Local\Programs\Python\Python38-32\pyyy\fu1.py
True
True
None
def area(radius):
b = 3.14159 * radius**2
return b
Parameters:
Parameters are passed during the definition of function while Arguments are passed during
the function call.
Example:
#here a and b are parameters
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/paraarg.py
25
#function defination
def display():
print("vandemataram")
95
PYTHON PROGRAMMING III YEAR/I SEM MRCET
print("i am in main")
#function call
display()
print("i am in main")
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/fu1.py
i am in main
vandemataram
i am in main
def Fun1() :
print("function 1")
Fun1()
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/fu1.py
function 1
def fun2(a) :
print(a)
fun2("hello")
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/fu1.py
Hello
def fun3():
return "welcome to python"
print(fun3())
96
PYTHON PROGRAMMING III YEAR/I SEM MRCET
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/fu1.py
welcome to python
def fun4(a):
return a
print(fun4("python is better then c"))
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/fu1.py
A variable which is defined inside a function is local to that function. 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. It will be
visible throughout the file, and also inside any file which imports that file.
The variable defined inside a function can also be made global by using the global
statement.
def function_name(args):
.............
global x #declaring global variable inside a function
..............
97
PYTHON PROGRAMMING III YEAR/I SEM MRCET
x = "global"
def f():
print("x inside :", x)
f()
print("x outside:", x)
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/fu1.py
x inside : global
x outside: global
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)
The output shows an error, because we are trying to access a local variable y in a global
scope whereas the local variable only works inside f2() or local scope.
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.py
globalglobal
local
In the above code, we declare x as a global and y as a local variable in the f3(). Then,
we use multiplication operator * to modify the global variable x and we print
both x and y.
After calling the f3(), the value of x becomes global global because we used the x *
2 to print two times global. After that, we print the value of local variable y i.e local.
x=5
def f4():
x = 10
print("local x:", x)
f4()
print("global x:", x)
99
PYTHON PROGRAMMING III YEAR/I SEM MRCET
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/fu1.py
local x: 10
global x: 5
Function Composition:
Having two (or more) functions where the output of one function is the input for another. So
for example if you have two functions FunctionA and FunctionB you compose them by
doing the following.
FunctionB(FunctionA(x))
Here x is the input for FunctionA and the result of that is the input for FunctionB.
Example 1:
In the above program we tried to compose n functions with the main function created.
Example 2:
>>> colors=('red','green','blue')
>>> fruits=['orange','banana','cherry']
>>> zip(colors,fruits)
100
PYTHON PROGRAMMING III YEAR/I SEM MRCET
<zip object at 0x03DAC6C8>
>>> list(zip(colors,fruits))
Recursion:
Recursion is the process of defining something in terms of itself.
We know that in Python, a function can call other functions. It is even possible for the
function to call itself. These type of construct are termed as recursive functions.
Factorial of a number is the product of all the integers from 1 to that number. For example,
the factorial of 6 (denoted as 6!) is 1*2*3*4*5*6 = 720.
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/rec.py
zero factorial 1
five factorial 120
def calc_factorial(x):
"""This is a recursive function
to find the factorial of an integer"""
if x == 1:
return 1
else:
return (x * calc_factorial(x-1))
101
PYTHON PROGRAMMING III YEAR/I SEM MRCET
num = 4
print("The factorial of", num, "is", calc_factorial(num))
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/rec.py
The factorial of 4 is 24
Python arrays:
Array is a container which can hold a fix number of items and these items should be of the
same type. Most of the data structures make use of arrays to implement their algorithms.
Following are the important terms to understand the concept of Array.
Array Representation
Int array [10] = {10, 20, 30, 40, 50, 60, 70, 80, 85, 90}
As per the above illustration, following are the important points to be considered.
Index starts with 0.
Array length is 10 which means it can store 10 elements.
Each element can be accessed via its index. For example, we can fetch an element at
index 6 as 70
Basic Operations
102
PYTHON PROGRAMMING III YEAR/I SEM MRCET
Deletion − Deletes an element at the given index.
Search − Searches an element using the given index or by the value.
Update − Updates an element at the given index.
Array is created in Python by importing array module to the python program. Then the
array is declared as shown below.
from array import *
arrayName=array(typecode, [initializers])
Typecode are the codes that are used to define the type of value the array will hold. Some
common typecodes used are:
Typecode Value
b Represents signed integer of size 1 byte/td>
103
PYTHON PROGRAMMING III YEAR/I SEM MRCET
c Represents character of size 1 byte
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.py
10
20
30
40
50
We can access each element of an array using the index of the element.
104
PYTHON PROGRAMMING III YEAR/I SEM MRCET
Output:
RESTART: C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/arr2.py
10
30
Array methods:
Python has a set of built-in methods that you can use on lists/arrays.
Method Description
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
105
PYTHON PROGRAMMING III YEAR/I SEM MRCET
Note: Python does not have built-in support for Arrays, but Python Lists can be used instead.
Example:
>>> college=["mrcet","it","cse"]
>>> college.append("autonomous")
>>> college
>>> college.append("eee")
>>> college.append("ece")
>>> college
>>> college.pop()
'ece'
>>> college
>>> college.pop(4)
'eee'
>>> college
>>> college.remove("it")
>>> college
106
PYTHON PROGRAMMING III YEAR/I SEM MRCET
UNIT – IV
FILES,EXCEPTIONS
File I/O, Exception Handling, introduction to basic standard libraries, Installation of pip,
Demonstrate Modules: Turtle, pandas, numpy, pdb, Explore packages.
A file is some information or data which stays in the computer storage devices. Python gives
you easy ways to manipulate these files. Generally files divide in two categories,
text file and binary file. Text files are simple text where as the binary files contain binary
data which is only readable by computer.
Text files: In this type of file, Each line of text is terminated with a special character
called EOL (End of Line), which is the new line character („\n‟) in python by default.
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.
An exception is an event, which occurs during the execution of a program that disrupts the
normal flow of the program's instructions. In general, when a Python script encounters a
situation that it cannot cope with, it raises an exception. An exception is a Python object
that represents an error.
Text files:
We declared the variable f to open a file named hello.txt. 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
107
PYTHON PROGRAMMING III YEAR/I 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
Mode Description
'x' Creates a new file. If file already exists, the operation fails.
'+' This will open a file for reading and writing (updating)
The following image shows how to create and open a text file in notepad from command
prompt
108
PYTHON PROGRAMMING III YEAR/I SEM MRCET
(or)
a=open(“one.txt”,”r”)
print(a.read())
109
PYTHON PROGRAMMING III YEAR/I SEM MRCET
a.close()
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/filess/f1.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.close() ---- This will close the instance of the file somefile.txt stored
# Write a python program to open and write “hello world” into a file?
f=open("1.txt","a")
f.write("hello world")
f.close()
Output:
110
PYTHON PROGRAMMING III YEAR/I SEM MRCET
(or)
Note: In the above program the 1.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.
f=open("1.txt",'w')
f.close()
Output:
In the above program the hello txt file consist of data like
111
PYTHON PROGRAMMING III YEAR/I 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.
fo=open("abc.txt","w+")
fo.write("Python Programming")
print(fo.read())
fo.close()
Output:
(or)
Note: It creates the abc.txt file automatically and writes the data into it
112
PYTHON PROGRAMMING III YEAR/I SEM MRCET
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.
The command line arguments in python can be processed by using either „sys‟ module,
„argparse‟ module and „getopt‟ module.
„sys‟ module :
Python sys module stores the command line arguments into a list, we can access it
using sys.argv. This is very useful and simple way to read command line arguments as
String.
sys.argv is the list of commandline arguments passed to the Python program. argv represents
all the items that come along via the command line input, it's basically an array holding the
command line arguments of our program
>>> sys.modules.keys() -- this prints so many dict elements in the form of list.
# Python code to demonstrate the use of 'sys' module for command line arguments
import sys
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/cmndlinarg.py
['C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/cmndlinarg.py']
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/cmndlinarg.py
113
PYTHON PROGRAMMING III YEAR/I SEM MRCET
Note: Since my list consist of only one element at „0‟ index so it prints only that list
element, if we try to access at index position „1‟ then it shows the error like,
import sys
print(type(sys.argv))
print('The command line arguments are:')
for i in sys.argv:
print(i)
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/symod.py ==
<class 'list'>
The command line arguments are:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/symod.py
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/s1.py =
System version is:
3.8.0 (tags/v3.8.0:fa919fd, Oct 14 2019, 19:21:23) [MSC v.1916 32 bit (Intel)]
Version Information is:
sys.version_info(major=3, minor=8, micro=0, releaselevel='final', serial=0)
„argparse‟ module :
Python getopt module is very similar in working as the C getopt() function for parsing
command-line parameters. Python getopt module is useful in parsing command line
arguments where we want user to enter some options too.
114
PYTHON PROGRAMMING III YEAR/I SEM MRCET
import argparse
parser = argparse.ArgumentParser()
print(parser.parse_args())
„getopt‟ module :
Python argparse module is the preferred way to parse command line arguments. 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. The signature of this function is
mentioned below:
import getopt
import sys
argv = sys.argv[0:]
try:
opts, args = getopt.getopt(argv, 'hm:d', ['help', 'my_file='])
#print(opts)
print(args)
except getopt.GetoptError:
# Print a message or do something useful
print('Something went wrong!')
sys.exit(2)
115
PYTHON PROGRAMMING III YEAR/I SEM MRCET
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/gtopt.py ==
['C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/gtopt.py']
Python Errors and Built-in Exceptions: Python (interpreter) raises exceptions when it
encounters errors. When writing a program, we, more often than not, will
encounter 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.
OverflowError:
OverflowError in Python indicates that an arithmetic operation has exceeded the limits of
the current Python runtime. This is typically due to excessively large float values, as integer
values that are too big will opt to raise memory errors instead.
ImportError:
It is raised when you try to import a module which does not exist. This may happen if you
made a typing mistake in the module name or the module doesn't exist in its standard path.
In the example below, a module named "non_existing_module" is being imported but it
doesn't exist, hence an import error exception is raised.
IndexError:
An IndexError exception is raised when you refer a sequence which is out of range. In the
example below, the list abc contains only 3 entries, but the 4th index is being accessed,
which will result an IndexError exception.
TypeError:
When two unrelated type of objects are combined, TypeErrorexception is raised.In example
below, an int and a string is added, which will result in TypeError exception.
116
PYTHON PROGRAMMING III YEAR/I SEM MRCET
IndentationError:
Unexpected indent. As mentioned in the "expected an indentedblock" section, Python not
only insists on indentation, it insists on consistentindentation. You are free to choose the
number of spaces of indentation to use, but you then need to stick with it.
Syntax errors:
These are the most basic type of error. They arise when the Python parser is unable to
understand a line of code. Syntax errors are almost always fatal, i.e. there is almost never a
way to successfully execute a piece of code containing syntax errors.
Run-time error:
A run-time error happens when Python understands what you are saying, but runs into
trouble when following your instructions.
Key Error :
Value Error:
In Python, a value is the information that is stored within a certain object. To encounter a
ValueError in Python means that is a problem with the content of the object you tried to
assign the value to.
Python has many built-in exceptions which forces your program to output an error when
something in it goes wrong. In Python, users can define such exceptions by creating a new
class. This exception class has to be derived, either directly or indirectly,
from Exception class.
ArrayIndexOutOfBoundException.
ClassNotFoundException.
FileNotFoundException.
IOException.
InterruptedException.
NoSuchFieldException.
NoSuchMethodException
117
PYTHON PROGRAMMING III YEAR/I SEM MRCET
Handling Exceptions:
The cause of an exception is often external to the program itself. For example, an incorrect
input, a malfunctioning IO device etc. Because the program abruptly terminates on
encountering an exception, it may cause damage to system resources, such as files. Hence,
the exceptions should be properly handled so that an abrupt termination of the program is
prevented.
Python uses try and except keywords to handle exceptions. Both keywords are followed by
indented blocks.
Syntax:
try :
except :
Logical errors (2+2=4, instead if we get output as 3 i.e., wrong output …..,),
As a developer we test the application, during that time logical error may obtained.
Run time error (In this case, if the user doesn‟t know to give input, 5/6 is ok but if
the user say 6 and 0 i.e.,6/0 (shows error a number cannot be divided by zero))
This is not easy compared to the above two errors because it is not done by the
system, it is (mistake) done by the user.
1. You should be able to understand the mistakes; the error might be done by user, DB
connection or server.
2. Whenever there is an error execution should not stop.
Ex: Banking Transaction
3. The aim is execution should not stop even though an error occurs.
118
PYTHON PROGRAMMING III YEAR/I 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.py
2.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)
Output:
Traceback (most recent call last):
print(a/b)
119
PYTHON PROGRAMMING III YEAR/I SEM MRCET
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/ex3.py
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("bye")
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/ex4.py
2.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.
a=5
b=0
try:
120
PYTHON PROGRAMMING III YEAR/I SEM MRCET
print(a/b)
except Exception as e:
print("bye")
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/ex5.py
bye
(Type of error)
a=5
b=2
try:
print("resource opened")
print(a/b)
print("resource closed")
except Exception as e:
print("number can not be divided by zero",e)
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/ex6.py
resource opened
2.5
resource closed
121
PYTHON PROGRAMMING III YEAR/I SEM MRCET
Note: the file is opened and closed well, but see by changing the value of b to 0,
a=5
b=0
try:
print("resource opened")
print(a/b)
print("resource closed")
except Exception as e:
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/ex7.py
resource opened
b=0
try:
print("resource opened")
print(a/b)
except Exception as e:
print("resource closed")
Output:
122
PYTHON PROGRAMMING III YEAR/I SEM MRCET
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/ex8.py
resource opened
resource closed
The result is fine that the file is opened and closed, but again change the value of
b to back (i.e., value 2 or other than zero)
a=5
b=2
try:
print("resource opened")
print(a/b)
except Exception as e:
print("number can not be divided by zero",e)
print("resource closed")
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/ex9.py
resource opened
2.5
try:
123
PYTHON PROGRAMMING III YEAR/I 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
the value can not be divided by zero division by zero
resource closed
change the value of b to 2 for above program, you see the output like
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/ex10.py
resource open
2.5
enter a number 6
6
resource closed
Instead give input as some character or string for above program, check the
output
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/ex10.py
resource open
2.5
enter a number p
resource closed
Traceback (most recent call last):
File "C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/ex10.py", line
7, in <module>
k=int(input("enter a number"))
ValueError: invalid literal for int() with base 10: ' p'
124
PYTHON PROGRAMMING III YEAR/I SEM MRCET
#
a=5
b=0
try:
print("resource open")
print(a/b)
k=int(input("enter a number"))
print(k)
125
PYTHON PROGRAMMING III YEAR/I SEM MRCET
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...",e)
finally:
print("resource closed")
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/ex11.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.py
resource open
2.5
enter a number p
invalid input
resource closed
126
PYTHON PROGRAMMING III YEAR/I SEM MRCET
• We can define our most used functions in a module and import it, instead of copying
their definitions into different programs.
Advantages :
• Simplicity: Rather than focusing on the entire problem at hand, a module typically
focuses on one relatively small portion of the problem. If you‟re working on a single
module, you‟ll have a smaller problem domain to wrap your head around. This makes
development easier and less error-prone.
• Functions, modules and packages are all constructs in Python that promote code
modularization.
A file containing Python code, for e.g.: example.py, is called a module and its module name
would be example.
result=a+b
127
PYTHON PROGRAMMING III YEAR/I SEM MRCET
return result
"""This program adds two numbers and return the result""“
128
PYTHON PROGRAMMING III YEAR/I SEM MRCET
Here, we have defined a function add() inside a module named example. The function takes
in two numbers and returns their sum.
• Using the module name we can access the function using dot (.) operation. For Eg:
>>> example.add(5,5)
10
• Python has a ton of standard modules available. Standard modules can be imported
the same way as we import our user-defined modules.
Reloading a module:
def hi(a,b):
print(a+b)
hi(4,4)
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/add.py
129
PYTHON PROGRAMMING III YEAR/I SEM MRCET
>>> import add
>>> import add
>>>
Python provides a neat way of doing this. We can use the reload() function inside
the imp module to reload a module. This is how its done.
• This code got executed >>> import my_module >>> imp.reload(my_module) This
code got executed <module 'my_module' from '.\\my_module.py'>how its done.
>>> imp.reload(add)
>>> dir(example)
[' builtins ', ' cached ', ' doc ', ' file ', ' loader ', ' name ', ' package ',
' spec ', 'add']
>>> dir()
[' annotations ', ' builtins ', ' doc ', ' file ', ' loader ', ' name ',
' package ', ' spec ', ' warningregistry ', 'add', 'example', 'hi', 'imp']
Datetime module:
>>> a=datetime.datetime(2019,5,27,6,35,40)
>>> a
import datetime
a=datetime.date(2000,9,18)
print(a)
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/d1.py =
2000-09-18
import datetime
a=datetime.time(5,3)
print(a)
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/d1.py =
05:03:00
#write a python program to print date, time for today and now.
import datetime
131
PYTHON PROGRAMMING III YEAR/I SEM MRCET
a=datetime.datetime.today()
b=datetime.datetime.now()
print(a)
print(b)
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/d1.py =
2019-11-29 12:49:52.235581
2019-11-29 12:49:52.235581
#write a python program to add some days to your present date and print the date
added.
import datetime
a=datetime.date.today()
b=datetime.timedelta(days=7)
print(a+b)
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/d1.py =
2019-12-06
#write a python program to print the no. of days to write to reach your birthday
import datetime
a=datetime.date.today()
b=datetime.date(2020,5,27)
c=b-a
print(c)
Output:
132
PYTHON PROGRAMMING III YEAR/I SEM MRCET
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/d1.py =
180 days, 0:00:00
#write an python program to print date, time using date and time functions
import datetime
t=datetime.datetime.today()
print(t.date())
print(t.time())
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/d1.py =
2019-11-29
12:53:39.226763
Time module:
print(time.time())
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/t1.py =
1575012547.1584706
import time
print(time.localtime(time.time()))
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/t1.py =
133
PYTHON PROGRAMMING III YEAR/I SEM MRCET
time.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)
import time
a=(1999,5,27,7,20,15,1,27,0)
print(time.mktime(a))
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/t1.py =
927769815.0
print("Python Lab")
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/t1.py =
os module:
>>> import os
>>> os.name
'nt'
>>> os.getcwd()
'C:\\Users\\MRCET\\AppData\\Local\\Programs\\Python\\Python38-32\\pyyy'
>>> os.mkdir("temp1")
134
PYTHON PROGRAMMING III YEAR/I SEM MRCET
>>> os.getcwd()
'C:\\Users\\MRCET\\AppData\\Local\\Programs\\Python\\Python38-32\\pyyy'
>>> open("t1.py","a")
>>> os.access("t1.py",os.F_OK)
True
>>> os.access("t1.py",os.W_OK)
True
>>> os.rename("t1.py","t3.py")
>>> os.access("t1.py",os.F_OK)
False
>>> os.access("t3.py",os.F_OK)
True
>>> os.rmdir('temp1')
(or)
os.rmdir('C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/temp1')
135
PYTHON PROGRAMMING III YEAR/I SEM MRCET
>>> os.remove("t3.py")
Note: We can check with the following cmd whether removed or not
>>> os.access("t3.py",os.F_OK)
False
>>> os.listdir()
['add.py', 'ali.py', 'alia.py', 'arr.py', 'arr2.py', 'arr3.py', 'arr4.py', 'arr5.py', 'arr6.py', 'br.py',
'br2.py', 'bubb.py', 'bubb2.py', 'bubb3.py', 'bubb4.py', 'bubbdesc.py', 'clo.py', 'cmndlinarg.py',
'comm.py', 'con1.py', 'cont.py', 'cont2.py', 'd1.py', 'dic.py', 'e1.py', 'example.py', 'f1.y.py',
'flowof.py', 'fr.py', 'fr2.py', 'fr3.py', 'fu.py', 'fu1.py', 'if1.py', 'if2.py', 'ifelif.py', 'ifelse.py',
'iff.py', 'insertdesc.py', 'inserti.py', 'k1.py', 'l1.py', 'l2.py', 'link1.py', 'linklisttt.py', 'lis.py',
'listlooop.py', 'm1.py', 'merg.py', 'nesforr.py', 'nestedif.py', 'opprec.py', 'paraarg.py',
'qucksort.py', 'qukdesc.py', 'quu.py', 'r.py', 'rec.py', 'ret.py', 'rn.py', 's1.py', 'scoglo.py',
'selecasce.py', 'selectdecs.py', 'stk.py', 'strmodl.py', 'strr.py', 'strr1.py', 'strr2.py', 'strr3.py',
'strr4.py', 'strrmodl.py', 'wh.py', 'wh1.py', 'wh2.py', 'wh3.py', 'wh4.py', 'wh5.py',
' pycache ']
>>> os.listdir('C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32')
Calendar module:
136
PYTHON PROGRAMMING III YEAR/I SEM MRCET
#write a python program to display a particular month of a year using calendar
module.
import calendar
print(calendar.month(2020,1))
Output:
# write a python program to check whether the given year is leap or not.
import calendar
print(calendar.isleap(2021))
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/cl1.py
False
print(calendar.calendar(2020,1,1,1))
Output:
137
PYTHON PROGRAMMING III YEAR/I SEM MRCET
math module:
# write a python program which accepts the radius of a circle from user and computes
the area.
import math
r=int(input("Enter radius:"))
area=math.pi*r*r
Output:
138
PYTHON PROGRAMMING III YEAR/I SEM MRCET
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/m.py =
Enter radius:4
• For Eg:
• We have renamed the math module as m. This can save us typing time in some cases.
• Note that the name math is not recognized in our scope. Hence, math.pi is
invalid, m.pi is the correct implementation.
• In such case we don't use the dot operator. We could have imported multiple attributes
as follows.
139
PYTHON PROGRAMMING III YEAR/I SEM MRCET
>>> from math import pi, e
>>> pi
3.141592653589793
>>> e
2.718281828459045
• We can import all names(definitions) from a module using the following construct.
• We imported all the definitions from the math module. This makes all names except
those beginnig with an underscore, visible in our scope.
Explore packages:
• We don't usually store all of our files in our computer in the same location. We use a
well-organized hierarchy of directories for easier access.
• Similar files are kept in the same directory, for example, we may keep all the songs in
the "music" directory. Analogous to this, Python has packages for directories
and modules for files.
• 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. This
makes a project (program) easy to manage and conceptually clear.
• Similar, as a directory can contain sub-directories and files, a Python package can
have sub-packages and modules.
• A directory must contain a file named init .py in order for Python to consider it as
a package. This file can be left empty but we generally place the initialization code for
that package in this file.
140
PYTHON PROGRAMMING III YEAR/I SEM MRCET
• If a file named init .py is present in a package directory, it is invoked when the
package or a module in the package is imported. This can be used for execution of
package initialization code, such as initialization of package-level data.
• We can import modules from packages using the dot (.) operator.
• For example, if want to import the start module in the above example, it is done as
follows.
• import Game.Level.start
• Now if this module contains a function named select_difficulty(), we must use the
full name to reference it.
• Game.Level.start.select_difficulty(2)
141
PYTHON PROGRAMMING III YEAR/I SEM MRCET
• If this construct seems lengthy, we can import the module without the package prefix
as follows.
• from Game.Level import start
• start.select_difficulty(2)
• Yet another way of importing just the required function (or class or variable) form a
module within a package would be as follows.
• select_difficulty(2)
Examples:
print("Department")
def write():
print("Student")
Output:
>>> from IIYEAR.CSE import student
>>> student.read()
Department
>>> student.write()
Student
>>> read
142
PYTHON PROGRAMMING III YEAR/I SEM MRCET
<function read at 0x03BD1070>
>>> read()
Department
>>> write()
Student
c=a+b
return c
Output:
C:\Users\MRCET\AppData\Local\Programs\Python\Python38-32\IIYEAR\modu1.py
>>> modu1.add()
10
def a():
print("hello world")
a()
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/IIYEAR/exam.py
hello world
hello world
143
PYTHON PROGRAMMING III YEAR/I SEM MRCET
Installation of pip:PIP is a package manager for Python packages, or modules if you like.
Note: If you have Python version 3.4 or later, PIP is included by default.
Package : A package contains all the files you need for a module.
Modules are Python code libraries you can include in your project.
Navigate your command line to the location of Python's script directory, and type the following:
Example
If you do not have PIP installed, you can download and install it from this
page: https://pypi.org/project/pip/
Download a Package
Open the command line interface and tell PIP to download the package you want.
Navigate your command line to the location of Python's script directory, and type the following:
Example
144
PYTHON PROGRAMMING III YEAR/I SEM MRCET
Using a Package:-
Example
import camelcase
c = camelcase.CamelCase()
print(c.hump(txt))
Example
The PIP Package Manager will ask you to confirm that you want to remove the camelcase
package:
Uninstalling camelcase-02.1:
Would remove:
c:\users\Your Name\appdata\local\programs\python\python36-32\lib\site-packages\camecase-
0.2-py3.6.egg-info
c:\users\Your Name\appdata\local\programs\python\python36-32\lib\site-packages\camecase\*
Proceed (y/n)?
Turtle: Turtle is a special feathers of Python. Using Turtle, we can easily draw in a drawing
board. First we import the turtle module. Then create a window, next we create turtle object
and using turtle method we can draw in the drawing board.
Some turtle method
METHOD PARAMETER DESCRIPTION
fillcolor() Color name Changes the color of the turtle will use to fill a polygon
146
PYTHON PROGRAMMING III YEAR/I SEM MRCET
position() None It returns the current position
end_fill() None It closes the polygon and fills with the current fill color
Example code
Output
147
PYTHON PROGRAMMING III YEAR/I SEM MRCET
Output
Output
Output
149
PYTHON PROGRAMMING III YEAR/I SEM MRCET
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 the top of the NumPy
library. Pandas is fast and it has high-performance & productivity for users.
Getting Started : After the pandas has 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. However, it is not necessary to import the library
using alias, it just helps in writing less amount of code everytime a method or property is called.
Pandas generally provide two data structure for manipulating data, They are:
Series
DataFrame
150
PYTHON PROGRAMMING III YEAR/I SEM MRCET
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 index. 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, and 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
print(ser)
# simple array
data = np.array(['g', 'e', 'e', 'k', 's'])
151
PYTHON PROGRAMMING III YEAR/I SEM MRCET
ser = pd.Series(data)
print(ser)
Output:
Series([], dtype: float64)
0 g
1 e
2 e
3 k
4 s
dtype: object
DataFrame
152
PYTHON PROGRAMMING III YEAR/I SEM MRCET
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, and Excel file. Pandas
DataFrame can be created from the lists, dictionary, and from a list of dictionary etc.
Example:
import pandas as pd
# list of strings
lst = ['aaa', 'bbb', 'ccc']
Output:
Empty DataFrame
Columns: []
Index: []
0
0 aaa
1 bbb
2 ccc
153
PYTHON PROGRAMMING III YEAR/I SEM MRCET
Python Numpy
Numpy is a general-purpose array-processing package. It provides a high-performance
multidimensional array object, and tools for working with these arrays. It is the fundamental
package for scientific computing with Python.
Besides its obvious scientific uses, Numpy can also be used as an efficient multi-dimensional
container of generic data.
Arrays in Numpy
Array in Numpy is a table of elements (usually numbers), all of the same type, indexed by a tuple
of positive integers. In Numpy, number of dimensions of the array is called rank of the array.A
tuple of integers giving the size of the array along each dimension is known as shape of the array.
An array class in Numpy is called as ndarray. Elements in Numpy arrays are accessed by using
square brackets and can be initialized by using nested Python Lists.
154
PYTHON PROGRAMMING III YEAR/I SEM MRCET
Output:
Array with Rank 1:
[1 2 3]
Array with Rank 2:
[[1 2 3]
[4 5 6]]
# Initial Array
arr = np.array([[-1, 2, 0, 4],
[4, -0.5, 6, 0],
[2.6, 0, 7, 8],
[3, -7, 4, 2.0]])
print("Initial Array: ")
print(arr)
# Printing elements at
# specific Indices
Index_arr = arr[[1, 1, 0, 3],
[3, 2, 1, 0]]
print ("\nElements at indices (1, 3), "
155
PYTHON PROGRAMMING III YEAR/I SEM MRCET
"(1, 2), (0, 1), (3, 0):\n", Index_arr)
Output:
Initial Array:
[[-1. 2. 0. 4. ]
[ 4. -0.5 6. 0. ]
[ 2.6 0. 7. 8. ]
[ 3. -7. 4. 2. ]]
Array with first 2 rows and alternate columns(0 and 2):
[[-1. 0.]
[ 4. 6.]]
Elements at indices (1, 3), (1, 2), (0, 1), (3, 0):
[ 0. 54. 2. 3.]
Array Operations : In numpy, arrays allow a wide range of operations which can be performed
on a particular array or a combination of Arrays. These operation include some basic Mathematical
operation as well as Unary and Binary operations.
# Python program to demonstrate
# basic operations on single array
import numpy as np
# Defining Array 1
a = np.array([[1, 2],
[3, 4]])
# Defining Array 2
b = np.array([[4, 3],
[2, 1]])
156
PYTHON PROGRAMMING III YEAR/I SEM MRCET
# sum of array elements
# Performing Unary operations
print ("\nSum of all array "
"elements: ", a.sum())
Output:
Adding 1 to every element:
[[2 3]
[4 5]]
Array sum:
[[5 5]
[5 5]]
157
PYTHON PROGRAMMING III YEAR/I SEM MRCET
Pdb:
In software development jargon, 'debugging' term is popularly used to process of locating and
rectifying errors in a program. Python's standard library contains pdb module which is a set of
utilities for debugging of Python programs.
The debugging functionality is defined in a Pdb class. The module internally makes used of bdb
and cmd modules.
The pdb module has a very convenient command line interface. It is imported at the time of
execution of Python script by using –m switch
def fact(x):
f=1
for i in range(1,x+1):
print (i)
f=f*i
return f
if name ==" main ":
print ("factorial of 3=",fact(3))
Start debugging this module from command line. In this case the execution halts at first line in the
code by showing arrow (->) to its left, and producing debugger prompt (Pdb)
158
PYTHON PROGRAMMING III YEAR/I SEM MRCET
The list command lists entire code with -> symbol to the left of a line at which program has halted.
(Pdb) list
1 -> def fact(x):
2 f=1
3 for i in range(1,x+1):
4 print (i)
5f=f*i
6 return f
7 if name ==" main ":
8 print ("factorial of 3 = ", fact(3))
To move through the program line by line use step or next command.
(Pdb) step
> c:\python36\fact.py(7)<module>()
-> if name ==" main ":
(Pdb) next
> c:\python36\fact.py(8)<module>()
-> print ("factorial of 3 = ", fact(3))
159
PYTHON PROGRAMMING III YEAR/I SEM MRCET
(Pdb) next
1
2
3
factorial of 3= 6
--Return--
> c:\python36\fact.py(8)<module>()->None
-> print ("factorial of 3 = ", fact(3))
160
PYTHON PROGRAMMING III YEAR/I SEM MRCET
UNIT-V
OOPS FRAMEWORK :
An object-oriented paradigm is to design the program using classes and objects. The object is
related to real-word entities such as book, house, pencil, etc. The oops concept focuses on writing
the reusable code. It is a widespread technique to solve the problem by creating objects.
Object : The object is an entity that has state and behavior. It may be any real-world object like
the mouse, keyboard, chair, table, pen, etc.
Everything in Python is an object, and almost everything has attributes and methods. All functions
have a built-in attribute doc , which returns the docstring defined in the function source code.
When we define a class, it needs to create an object to allocate the memory. Consider the
following example.
Example:
class car:
def init (self,modelname, year):
self.modelname = modelname
self.year = year
def display(self):
print(self.modelname,self.year)
c1 = car("Toyota", 2016)
c1.display()
Output:
Toyota 2016
161
PYTHON PROGRAMMING III YEAR/I SEM MRCET
In the above example, we have created the class named car, and it has two attributes modelname
and year. We have created a c1 object to access the class attribute. The c1 object will allocate
memory for these values.
Class : The class can be defined as a collection of objects. It is a logical entity that has some
specific attributes and methods. For example: if you have an employee class, then it should contain
an attribute and method, i.e. an email id, name, age, salary, etc.
Syntax
1. class ClassName:
2. <statement-1>
3. .
4. .
5. <statement-N>
Consider the following example to create a class Employee which contains two fields as
Employee id, and name.
The class also contains a function display(), which is used to display the information of
the Employee.
Example
1. class Employee:
2. id = 10
3. name = "Devansh"
4. def display (self):
5. print(self.id,self.name)
Here, the self is used as a reference variable, which refers to the current class object. It is always
the first argument in the function definition. However, using self is optional in the function call.
The self-parameter
The self-parameter refers to the current instance of the class and accesses the class variables. We
can use anything instead of self, but it must be the first parameter of any function which belongs to
the class.
162
PYTHON PROGRAMMING III YEAR/I SEM MRCET
A class needs to be instantiated if we want to use the class attributes in another class or method. A
class can be instantiated by calling the class using the class name.
<object-name> = <class-name>(<arguments>)
The following example creates the instance of the class Employee defined in the above example.
Example
class Employee:
1. id = 10
name = "John"
2. def display (self):
3. print("ID: %d \nName: %s"%(self.id,self.name))
4. # Creating a emp instance of Employee class
5. emp = Employee()
6. emp.display()
Output:
ID: 10
Name: John
In the above code, we have created the Employee class which has two attributes named id and
name and assigned value to them. We can observe we have passed the self as parameter in display
function. It is used to refer to the same class attribute.
We have created a new instance object named emp. By using it, we can access the attributes of the
class.
Python Inheritance
In inheritance, the child class acquires the properties and can access all the data members and
functions defined in the parent class. A child class can also provide its specific implementation
to the functions of the parent class. In this section of the tutorial, we will discuss inheritance in
detail.
163
PYTHON PROGRAMMING III YEAR/I SEM MRCET
In python, a derived class can inherit base class by just mentioning the base in the bracket after the
derived class name. Consider the following syntax to inherit a base class into the derived class.
1. Single Inheritance: Single inheritance enables a derived class to inherit properties from a
single parent class, thus enabling code reusability and addition of new features to existing
code.
Example:
# Base class
class Parent:
def func1(self):
print("This function is in parent class.")
# Derived class
class Child(Parent):
def func2(self):
print("This function is in child class.")
# Driver's code
object = Child()
object.func1()
object.func2()
Output :-
This function is in parent class.
This function is in child class.
164
PYTHON PROGRAMMING III YEAR/I SEM MRCET
2. Multiple Inheritance: When a class can be derived from more than one base classes this type
of inheritance is called multiple inheritance. In multiple inheritance, all the features of the
base classes are inherited into the derived class.
Example:
# Base class1
class Mother:
mothername = ""
def mother(self):
print(self.mothername)
# Base class2
class Father:
fathername = ""
def father(self):
print(self.fathername)
# Derived class
class Son(Mother, Father):
def parents(self):
print("Father :", self.fathername)
print("Mother :", self.mothername)
# Driver's code
s1 = Son()
s1.fathername = "RAM"
s1.mothername = "SITA"
s1.parents()
Output:
Father : RAM
Mother : SITA
165
PYTHON PROGRAMMING III YEAR/I SEM MRCET
3. Multilevel Inheritance
In multilevel inheritance, features of the base class and the derived class are further inherited
into the new derived class. This is similar to a relationship representing a child and
grandfather.
Example:
# Base class
class Grandfather:
grandfathername =""
def grandfather(self):
print(self.grandfathername)
# Intermediate class
class Father(Grandfather):
fathername = ""
def father(self):
print(self.fathername)
# Derived class
class Son(Father):
def parent(self):
print("GrandFather :", self.grandfathername)
print("Father :", self.fathername)
166
PYTHON PROGRAMMING III YEAR/I SEM MRCET
# Driver's code
s1 = Son()
s1.grandfathername = "Srinivas"
s1.fathername = "Ankush"
s1.parent()
Output:
GrandFather : Srinivas
Father : Ankush
1. Hierarchical Inheritance: When more than one derived classes are created from a single
base this type of inheritence is called hierarchical inheritance. In this program, we have a
parent (base) class and two child (derived) classes.
Example:
# Python program to demonstrate
# Hierarchical inheritance
# Base class
class Parent:
def func1(self):
print("This function is in parent class.")
# Derived class1
class Child1(Parent):
def func2(self):
print("This function is in child 1.")
# Derivied class2
167
PYTHON PROGRAMMING III YEAR/I SEM MRCET
class Child2(Parent):
def func3(self):
print("This function is in child 2.")
# Driver's code
object1 = Child1()
object2 = Child2()
object1.func1()
object1.func2()
object2.func1()
object2.func3()
Output:
This function is in parent class.
This function is in child 1.
This function is in parent class.
This function is in child 2.
2. Hybrid Inheritance: Inheritence consisting of multiple types of inheritence is called hybrid
inheritence.
Example:
class School:
def func1(self):
print("This function is in school.")
class Student1(School):
def func2(self):
print("This function is in student 1. ")
class Student2(School):
def func3(self):
print("This function is in student 2.")
# Driver's code
object = Student3()
object.func1()
object.func2()
Output:
This function is in school.
This function is in student 1.
169
PYTHON PROGRAMMING III YEAR/I SEM MRCET
Polymorphism in Python
The word polymorphism means having many forms. In programming, polymorphism means
same function name (but different signatures) being uses for different types.
Example of inbuilt polymorphic functions :
# Driver code
print(add(2, 3))
print(add(2, 3, 4))
Output:
5
9
class India():
def capital(self):
print("New Delhi is the capital of India.")
170
PYTHON PROGRAMMING III YEAR/I SEM MRCET
def language(self):
print("Hindi is the most widely spoken language of India.")
def type(self):
print("India is a developing country.")
class USA():
def capital(self):
print("Washington, D.C. is the capital of USA.")
def language(self):
print("English is the primary language of USA.")
def type(self):
print("USA is a developed country.")
obj_ind = India()
obj_usa = USA()
for country in (obj_ind, obj_usa):
country.capital()
country.language()
country.type()
Output:
New Delhi is the capital of India.
Hindi is the most widely spoken language of India.
India is a developing country.
Washington, D.C. is the capital of USA.
English is the primary language of USA.
USA is a developed country.
171
PYTHON PROGRAMMING III YEAR/I SEM MRCET
Encapsulation in Python
Encapsulation is one of the fundamental concepts in object-oriented programming (OOP). It
describes the idea of wrapping data and the methods that work on data within one unit. This puts
restrictions on accessing variables and methods directly and can prevent the accidental
modification of data. To prevent accidental change, an object’s variable can only be changed by an
object’s method. Those type of variables are known as private variable.
A class is an example of encapsulation as it encapsulates all the data that is member functions,
variables, etc.
Note: The init method is a constructor and runs as soon as an object of a class is instantiated.
# Python program to
# demonstrate protected members
# Protected member
self._a = 2
# Calling constructor of
# Base class
Base. init (self)
print("Calling protected member of base class: ")
print(self._a)
obj1 = Derived()
obj2 = Base()
class Polygon(ABC):
# abstract method
def noofsides(self):
pass
class Triangle(Polygon):
class Pentagon(Polygon):
173
PYTHON PROGRAMMING III YEAR/I SEM MRCET
def noofsides(self):
print("I have 5 sides")
class Hexagon(Polygon):
class Quadrilateral(Polygon):
# Driver code
R = Triangle()
R.noofsides()
K = Quadrilateral()
K.noofsides()
R = Pentagon()
R.noofsides()
K = Hexagon()
K.noofsides()
Output:
I have 3 sides
I have 4 sides
I have 5 sides
I have 6 sides
174
PYTHON PROGRAMMING III YEAR/I SEM MRCET
Django is a high-level Python web framework that encourages rapid development and clean,
pragmatic design. Django makes it easier to build better web apps quickly and with less code.
Note − Django is a registered trademark of the Django Software Foundation, and is licensed
under BSD License
History of Django
2003 − Started by Adrian Holovaty and Simon Willison as an internal project at the
Lawrence Journal-World newspaper.
2005 − Released July 2005 and named it Django, after the jazz guitarist Django Reinhardt.
2005 − Mature enough to handle several high-traffic sites.
Current − Django is now an open source project with contributors across the world.
Django – Design Philosophies
Django comes with the following design philosophies −
Loosely Coupled − Django aims to make each element of its stack independent of the
others.
Less Coding − Less code so in turn a quick development.
Don't Repeat Yourself (DRY) − Everything should be developed only in exactly one place
instead of repeating it again and again.
Fast Development − Django's philosophy is to do all it can to facilitate hyper-fast
development.
Clean Design − Django strictly maintains a clean design throughout its own code and
makes it easy to follow best web-development practices.
Advantages of Django
Here are few advantages of using Django which can be listed out here −
Object-Relational Mapping (ORM) Support − Django provides a bridge between the
data model and the database engine, and supports a large set of database systems including
MySQL, Oracle, Postgres, etc. Django also supports NoSQL database through Django-
nonrel fork. For now, the only NoSQL databases supported are MongoDB and google app
engine.
Multilingual Support − Django supports multilingual websites through its built-in
internationalization system. So you can develop your website, which would support
multiple languages.
175
PYTHON PROGRAMMING III YEAR/I SEM MRCET
Framework Support − Django has built-in support for Ajax, RSS, Caching and various
other frameworks.
Administration GUI − Django provides a nice ready-to-use user interface for
administrative activities.
Development Environment − Django comes with a lightweight web server to facilitate
end-to-end application development and testing.
DJANGO MVC - MVT Pattern
The Model-View-Template (MVT) is slightly different from MVC. In fact the main difference
between the two patterns is that Django itself takes care of the Controller part (Software Code that
controls the interactions between the Model and View), leaving us with the template. The
template is a HTML file mixed with Django Template Language (DTL).
The following diagram illustrates how each of the components of the MVT pattern interacts with
each other to serve a user request −
The developer provides the Model, the view and the template then just maps it to a URL and
Django does the magic to serve it to the user.
Django development environment consists of installing and setting up Python, Django, and a
Database System. Since Django deals with web application, it's worth mentioning that you would
need a web server setup as well.
Step 1 – Installing Python
Django is written in 100% pure Python code, so you'll need to install Python on your system.
Latest Django version requires Python 2.6.5 or higher
If you're on one of the latest Linux or Mac OS X distribution, you probably already have Python
installed. You can verify it by typing python command at a command prompt. If you see
something like this, then Python is installed.
176
PYTHON PROGRAMMING III YEAR/I SEM MRCET
$ python
Python 2.7.5 (default, Jun 17 2014, 18:11:42)
[GCC 4.8.2 20140120 (Red Hat 4.8.2-16)] on linux2
Otherwise, you can download and install the latest version of Python from the
link http://www.python.org/download.
Step 2 - Installing Django
Installing Django is very easy, but the steps required for its installation depends on your operating
system. Since Python is a platform-independent language, Django has one package that works
everywhere regardless of your operating system.
Windows Installation
We assume you have your Django archive and python installed on your computer.
First, PATH verification.
On some version of windows (windows 7) you might need to make sure the Path system variable
has the path the following C:\Python34\;C:\Python34\Lib\site-packages\django\bin\ in it, of
course depending on your Python version.
Then, extract and install Django.
c:\>cd c:\Django-x.xx
Next, install Django by running the following command for which you will need administrative
privileges in windows shell "cmd" −
c:\Django-x.xx>python setup.py install
To test your installation, open a command prompt and type the following command −
c:\>python -c "import django; print(django.get_version())"
If you see the current version of Django printed on screen, then everything is set.
OR
Launch a "cmd" prompt and type python then −
c:\> python
>>> import django
>>> django.VERSION
Step 3 – Database Setup
Django supports several major database engines and you can set up any of them based on your
comfort.
MySQL (http://www.mysql.com/)
PostgreSQL (http://www.postgresql.org/)
177
PYTHON PROGRAMMING III YEAR/I SEM MRCET
SQLite 3 (http://www.sqlite.org/)
Oracle (http://www.oracle.com/)
MongoDb (https://django-mongodb-engine.readthedocs.org)
GoogleAppEngine Datastore (https://cloud.google.com/appengine/articles/django-nonrel)
You can refer to respective documentation to installing and configuring a database of your choice.
Note − Number 5 and 6 are NoSQL databases.
Step 4 – Web Server
Django comes with a lightweight web server for developing and testing applications. This server
is pre-configured to work with Django, and more importantly, it restarts whenever you modify the
code.
However, Django does support Apache and other popular web servers such as Lighttpd. We will
discuss both the approaches in coming chapters while working with different examples.
As example let's say we want to build a website, the website is our project and, the forum, news,
contact engine are applications. This structure makes it easier to move an application between
projects since every application is independent.
Create a Project
Whether you are on Windows or Linux, just get a terminal or a cmd prompt and navigate to the
place you want your project to be created, then use this code −
$ django-admin startproject myproject
This will create a "myproject" folder with the following structure −
myproject/
manage.py
myproject/
init .py
settings.py
urls.py
wsgi.py
The Project Structure
The “myproject” folder is just your project container, it actually contains two elements −
manage.py − This file is kind of your project local django-admin for interacting with your
project via command line (start the development server, sync db...). To get a full list of
command accessible via manage.py you can use the code −
$ python manage.py help
The “myproject” subfolder − This folder is the actual python package of your project. It
contains four files −
178
PYTHON PROGRAMMING III YEAR/I SEM MRCET
o init .py − Just for python, treat this folder as package.
o settings.py − As the name indicates, your project settings.
o urls.py − All links of your project and the function to call. A kind of ToC of your
project.
o wsgi.py − If you need to deploy your project over WSGI.
Setting Up Your Project
Your project is set up in the subfolder myproject/settings.py. Following are some important
options you might need to set −
DEBUG = True
This option lets you set if your project is in debug mode or not. Debug mode lets you get more
information about your project's error. Never set it to ‘True’ for a live project. However, this has
to be set to ‘True’ if you want the Django light server to serve static files. Do it only in the
development mode.
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'database.sql',
'USER': '',
'PASSWORD': '',
'HOST': '',
'PORT': '',
}
}
Database is set in the ‘Database’ dictionary. The example above is for SQLite engine. As stated
earlier, Django also supports −
MySQL (django.db.backends.mysql)
PostGreSQL (django.db.backends.postgresql_psycopg2)
Oracle (django.db.backends.oracle) and NoSQL DB
MongoDB (django_mongodb_engine)
Before setting any new engine, make sure you have the correct db driver installed.
You can also set others options like: TIME_ZONE, LANGUAGE_CODE, TEMPLATE…
Now that your project is created and configured make sure it's working −
$ python manage.py runserver
You will get something like the following on running the above code −
179
PYTHON PROGRAMMING III YEAR/I SEM MRCET
Validating models...
0 errors found
September 03, 2015 - 11:41:50
Django version 1.6.11, using settings 'myproject.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
Create an Application
We assume you are in your project folder. In our main “myproject” folder, the same folder then
manage.py −
$ python manage.py startapp myapp
You just created myapp application and like project, Django create a “myapp” folder with the
application structure −
myapp/
init .py
admin.py
models.py
tests.py
views.py
init .py − Just to make sure python handles this folder as a package.
admin.py − This file helps you make the app modifiable in the admin interface.
models.py − This is where all the application models are stored.
tests.py − This is where your unit tests are.
views.py − This is where your application views are.
Get the Project to Know About Your Application
At this stage we have our "myapp" application, now we need to register it with our Django project
"myproject". To do so, update INSTALLED_APPS tuple in the settings.py file of your project
(add your app name) −
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'myapp',
)
180
PYTHON PROGRAMMING III YEAR/I SEM MRCET
Django provides a ready-to-use user interface for administrative activities. We all know how an
admin interface is important for a web project. Django automatically generates admin UI based on
your project models.
Starting the Admin Interface
The Admin interface depends on the django.countrib module. To have it working you need to
make sure some modules are imported in the INSTALLED_APPS and
MIDDLEWARE_CLASSES tuples of the myproject/settings.py file.
For INSTALLED_APPS make sure you have −
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'myapp',
)
For MIDDLEWARE_CLASSES −
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
Before launching your server, to access your Admin Interface, you need to initiate the database −
$ python manage.py migrate
syncdb will create necessary tables or collections depending on your db type, necessary for the
admin interface to run. Even if you don't have a superuser, you will be prompted to create one.
If you already have a superuser or have forgotten it, you can always create one using the
following code −
$ python manage.py createsuperuser
181
PYTHON PROGRAMMING III YEAR/I SEM MRCET
Now to start the Admin Interface, we need to make sure we have configured a URL for our admin
interface. Open the myproject/url.py and you should have something like −
from django.conf.urls import patterns, include, url
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'myproject.views.home', name = 'home'),
# url(r'^blog/', include('blog.urls')),
url(r'^admin/', include(admin.site.urls)),
)
Now just run the server.
$ python manage.py runserver
And your admin interface is accessible at: http://127.0.0.1:8000/admin/
Once connected with your superuser account, you will see the following screen −
182
PYTHON PROGRAMMING III YEAR/I SEM MRCET
That interface will let you administrate Django groups and users, and all registered models in
your app. The interface gives you the ability to do at least the "CRUD" (Create, Read, Update,
Delete) operations on your models.
183