BCA3RDPYTHON
BCA3RDPYTHON
BCA3RDPYTHON
Batch: 2019-2021
Python
Notes as per IKGPTU Syllabus
1
Unit-I
6-34
Python Data Types & Input/Output: Keywords, Identifiers, Python
Statement, Indentation, Documentation, Variables, Multiple Assignment,
Understanding Data Type, Data Type Conversion, Python Input and Output
Functions, Import command.
2
Unit-II
Unit-III
Unit-IV
Exception Handling: Exceptions, Built-in exceptions, Exception handling,
User defined exceptions in Python.
3
4
Unit- 1
5
What is Python?
Python is a popular programming language. It was created by Guido van Rossum, and released
in 1991.
It is used for:
Why Python?
Python works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc).
Python has a simple syntax similar to the English language.
Python has syntax that allows developers to write programs with fewer lines than some
other programming languages.
Python runs on an interpreter system, meaning that code can be executed as soon as it is
written. This means that prototyping can be very quick.
Python can be treated in a procedural way, an object-orientated way or a functional way.
6
ABC programming language is said to be the predecessor of Python language which was
capable of Exception Handling and interfacing with Amoeba Operating System.
Python is influenced by following programming languages:
o ABC language.
o Modula-3
Python Features
Python provides lots of features that are listed below.
7
Python is easy to learn and use. It is developer-friendly and high level programming language.
2) Expressive Language
Python language is more expressive means that it is more understandable and readable.
3) Interpreted Language
Python is an interpreted language i.e. interpreter executes the code line by line at a time. This makes
debugging easy and thus suitable for beginners.
4) Cross-platform Language
Python can run equally on different platforms such as Windows, Linux, Unix and Macintosh etc. So, we
can say that Python is a portable language.
Python language is freely available at offical web address.The source-code is also available. Therefore it
is open source.
6) Object-Oriented Language
Python supports object oriented language and concepts of classes and objects come into existence.
7) Extensible
It implies that other languages such as C/C++ can be used to compile the code and thus it can be used
further in our python code.
Python has a large and broad library and provides rich set of module and functions for rapid application
development.
8
Graphical user interfaces can be developed using Python.
10) Integrated
Speed
Python is slower than C or C++. But of course, Python is a high-level language, unlike C or
C++ it's not closer to hardware.
Mobile Development
Python is not a very good language for mobile development . It is seen as a weak language for
mobile computing. This is the reason very few mobile applications are built in it like
Carbonnelle.
Memory Consumption
Python is not a good choice for memory intensive tasks. Due to the flexibility of the data-types,
Python's memory consumption is also high.
Database Access
Python has limitations with database access . As compared to the popular technologies like
JDBC and ODBC, the Python's database access layer is found to be bit underdeveloped and
primitive . However, it cannot be applied in the enterprises that need smooth interaction of
complex legacy data .
Runtime Errors
Python programmers cited several issues with the design of the language. Because the language
is dynamically typed , it requires more testing and has errors that only show up at runtime .
9
If you’ve installed Python in Windows using the default installation options, the
path to the Python executable wasn’t added to the Windows Path variable. The
Path variable lists the directories that will be searched for executables when you
type a command in the command prompt. By adding the path to the Python
executable, you will be able to access python.exe by typing the python keyword
(you won’t need to specify the full path to the program).
Consider what happens if we enter the python command in the command prompt
and the path to that executable is not added to the Path variable:
C:\>python
As you can see from the output above, the command was not found. To
run python.exe, you need to specify the full path to the executable:
C:\>C:\Python34\python --version
Python 3.4.3
To add the path to the python.exe file to the Path variable, start the Run box and
enter sysdm.cpl:
This should open up the System Properties window. Go to the Advanced tab and
click the Environment Variables button:
10
In the System variable window, find the Path variable and click Edit:
11
Position your cursor at the end of the Variable value line and add the path to
the python.exe file, preceeded with the semicolon character (;). In our example,
we have added the following value: ;C:\Python34
Close all windows. Now you can run python.exe without specifying the full path
to the file:
12
C:>python --version
Python 3.4.3
Step 1) Open PyCharm Editor. You can see the introductory screen for PyCharm.
To create a new project, click on “Create New Project”.
13
1. You can select the location where you want the project to be created. If you
don’t want to change location than keep it as it is but at least change the
name from “untitled” to something more meaningful, like “FirstProject”.
2. PyCharm should have found the Python interpreter you installed earlier.
Step 3) Now Go up to the “File” menu and select “New”. Next, select “Python
File”.
Step 3) Now Go up to the “File” menu and select “New”. Next, select “Python File”.
14
Step 4) A new pop up will appear. Now type the name of the file you want (Here
we give “HelloWorld”) and hit “OK”.
Step 6) Now Go up to the “Run” menu and select “Run” to run your program.
15
Step 7) You can see the output of your program at the bottom of the screen.
help([object])
If the help function is passed without an argument, then the interactive help utility
starts up on the console.
16
Difference between python to other languages
1. Python programs are generally expected to run slower than Java programs.
2. Python supports a programming style that uses simple functions and
variables.
3. Python development is much quicker than having to write and debug a C or
C++.
4. Python shines as a glue language, used to combine components written in
C++
5. Python is one of the popular high-level programming languages used in an
extensive variety of application domains.
6. Python provides the ability to ‘write once, run anywhere’ that enables it to
run on all the operating systems which have Python installed.
7. Python has inbuilt garbage collection and dynamic memory allocation
process that enables efficient memory management.
8. Python is used as a scripting language, and at times it is also used for the
non-scripting purpose.
9. It is easier to write a code in Python as the number of lines is less
comparatively.
10. Python is an interpreted language and it runs through an interpreter during
compilation.
17
1. a = 1 + 2 + 3 + \
2. 4+5+6+\
3. 7+8+9
This is explicit line continuation. In Python, line continuation is implied
inside parentheses ( ), brackets [ ] and braces { }. For instance, we can
implement the above multi-line statement as
1. a = (1 + 2 + 3 +
2. 4+5+6+
3. 7 + 8 + 9)
Here, the surrounding parentheses ( ) do the line continuation implicitly.
Same is the case with [ ] and { }. For example:
1. colors = ['red',
2. 'blue',
3. 'green']
We could also put multiple statements in a single line using semicolons, as
follows
1. a = 1;
2. b = 2; c = 3
3.if statement
4.while statement
5for statement
6.input statement
7.print Statement ‘
Python Indentation
18
Generally four whitespaces are used for indentation and is preferred over
tabs.
Python Comments
Comments are very important while writing a program. It describes what's
going on inside a program so that a person looking at the source code does
not have a hard time figuring it out. You might forget the key details of the
program you just wrote in a month's time. So taking time to explain these
concepts in form of comments is always fruitful.
In Python, we use the hash (#) symbol to start writing a comment.
It extends up to the newline character. Comments are for programmers for
better understanding of a program. Python Interpreter ignores comment.
For Example
1. #This is a long comment
2. #and it extends
3. #to multiple lines
Python Keywords
Keywords are the reserved words in Python.
We cannot use a keyword as a variable name, function name or any other
identifier. They are used to define the syntax and structure of the Python
language.
In Python, keywords are case sensitive.
There are 33 keywords in Python 3.7. This number can vary slightly in
the course of time.
All the keywords except True, False and None are in lowercase and they
must be written as it is. The list of all the keywords is given below.
Keywords in Python
False class finally Is return
None continue for Lambda try
True def from nonlocal while
and del global Not with
as elif if Or yield
19
assert else import Pass
break except in Raise
Python Identifiers
An identifier is a name given to entities like class, functions, variables, etc. It helps
to differentiate one entity from another.
Python Variables
1. number = 10
As you can see from the above example, you can use the assignment operator = to
assign a value to a variable.
website = "String"
print(website)
20
Example 3: Assigning multiple values to multiple variables
a, b, c = 5, 3.2, "Hello"
print (a)
print (b)
print (c)
Constants
Create a constant.py
1. PI = 3.14
2. GRAVITY = 9.8
Create a main.py
1. import constant
2. print(constant.PI)
3. print(constant.GRAVITY)
3.14
9.8
21
Data Type in Python
Integers and floating points are separated by the presence or absence of a decimal
point. 5 is integer whereas 5.0 is a floating point number.
a=5
print(a)
# Output: 5
2. Python List
In Python programming, a list is created by placing all the items (elements) inside
a square bracket [ ], separated by commas.
It can have any number of items and they may be of different types (integer, float,
string etc.).
1. # list of integers
2. my_list = [1, 2, 3]
output
[1,2,3]
3.Python Tuple
A tuple in Python is similar to a list. The difference between the two is that we
cannot change the elements of a tuple once it is assigned whereas, in a list,
elements can be changed.
Creating a Tuple
23
A tuple is created by placing all the items (elements) inside parentheses (),
separated by commas. The parentheses are optional, however, it is a good practice
to use them.
A tuple can have any number of items and they may be of different types (integer,
float, list, string, etc.).
print(my_tuple)
# Output:
(1, 2, 3,4)
4.Python Strings
my_string = 'Hello'
print(my_string)
print(my_string)
5.Python Sets
However, the set itself is mutable. We can add or remove items from it.
Sets can be used to perform mathematical set operations like union, intersection,
symmetric difference etc.
A set is created by placing all the items (elements) inside curly braces {}, separated
by comma or by using the built-in function set().
# set of integers
my_set = {1, 2, 3}
print(my_set)
6.Python Dictionary
An item has a key and the corresponding value expressed as a pair, key: value.
1. int(a) : This function converts any data type to integer. ‘Base’ specifies the
base in which string is if data type is string.
2. float() : This function is used to convert any data type to a floating point
number
.
# initializing string
s = "10010"
s = "10010"
c = int(s)
print (c)
e = float(s)
print (e)
Output:
26
After converting to float : 10010.0
We use the print() function to output data to the standard output device (screen).
We can also output data to a file, but this will be discussed later. An example use is
given below.
a=5
Python Input
Up till now, our programs were static. The value of variables were defined or hard
coded into the source code.
To allow flexibility we might want to take the input from the user. In Python, we
have the input() function to allow this. The syntax for input() is
input([prompt])
27
#find sum of two number using input function
c=a+b
print(c)
Python Import
For example, we can import the math module by typing in import math.
import math
area=(math.pi)*r*r;
print(area)output:
3.141592653589793
Operators in Python
Operators are used to perform operations on variables and values.
Arithmetic operators
Assignment operators
28
Comparison operators
Logical operators
Identity operators
Membership operators
Bitwise operators
+ Addition x+y
- Subtraction x-y
* Multiplication x*y
/ Division x/y
% Modulus x%y
29
Operator Name Example
== Equal x == y
!= Not equal x != y
Identity operators are used to compare the objects, not if they are equal, but if they
are actually the same object, with the same memory location:
Operator Description Example
Returns true if both variables are
is x is y (same value)
the same object
Returns true if both variables are
is not x is not y (not same value)
not the same object
30
Membership operators are used to test if a sequence is presented in an object:
Python Expressions:
Expressions are representations of value. They are different from statement in the
fact that statements do something while expressions are representation of value.
For example any string is also an expressions since it represents the value of the
string as well. X+y,x-y,x*y
A=c+b
If(a>b):
While(a<=10):
Python has some advanced constructs through which you can represent values and
hence these constructs are also called expressions.
For example, the following code will get all the number within 10 and put them in
a list.
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
2.Dictionary comprehension
This is the same as list comprehension but will use curly braces:
{ k, v for k in iterable }
For example, the following code will get all the numbers within 5 as the keys and
will keep the corresponding squares of those numbers as the values.
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
3.Generator expression
For example, the following code will initialize a generator object that returns the
values within 10 when the object is called.
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
4.Conditional Expressions
32
You can use the following construct for one-liner conditions:
Example:
>>> x
'1'
Precedence Order
Associativity
When two operators share an operand and the operators have the same precedence,
then the expression is evaluated according to the associativity of the operators. For
example, since the ** operator has right-to-left associativity, a * b * c is treated
as a * (b * c). On the other hand, since the / operator has left-to-right
associativity, a / b / c is treated as (a / b) / c.
33
Precedence and Associativity of Python Operators
The Python documentation on operator precedence contains a table that shows all
Python operators from lowest to highest precedence, and notes their associativity.
Most programmers do not memorize them all, and those that do still use
parentheses for clarity.
Some operators like assignment operators and comparison operators do not have
associativity in Python. There are separate rules for sequences of this kind of
operator and cannot be expressed as associativity.
For example, x < y < z neither means (x < y) < z nor x < (y < z). x < y < z is
equivalent to x < y and y < z, and is evaluates from left-to-right.
34
Unit-2
35
Control Structures
Types
If statements
If-else statements
elif statements
Nested if and if ladder statements
elif ladder
2.Iteration Statements
While loop
For loop
3.break,Continue Statements
#1) If statements
If statement is one of the most commonly used conditional statement in most of the
programming languages. It decides whether certain statements need to be executed
or not. If statement checks for a given condition, if the condition is true, then the
set of code present inside the if block will be executed.
The If condition evaluates a Boolean expression and executes the block of code
only when the Boolean expression becomes TRUE.
Syntax:
36
If (Boolean expression): Block of code
flow chart
If you observe the above flow-chart, first the controller will come to an if condition
and evaluate the condition if it is true, then the statements will be executed,
otherwise the code present outside the block will be executed.
Example: 1
1 Num = 5
37
2.if else
The statement itself tells that if a given condition is true then execute the
statements present inside if block and if the condition is false then execute the else
block.
Else block will execute only when the condition becomes false, this is the block
where you will perform some actions when the condition is not true.
If-else statement evaluates the Boolean expression and executes the block of code
present inside the if block if the condition becomes TRUE and executes a block of
code present in the else block if the condition becomes FALSE.
Syntax:
if(Boolean expression):
else:
Here, the condition will be evaluated to a Boolean expression (true or false). If the
condition is true then the statements or program present inside the if block will be
executed and if the condition is false then the statements or program present inside
else block will be executed.
flowchart of if-else
38
If you observe the above flow chart, first the controller will come to if condition
and evaluate the condition if it is true and then the statements of if block will be
executed otherwise else block will be executed and later the rest of the code
present outside if-else block will be executed.
Example: 1
1 num = 5
4 else:
39
7 print(“This statement will always be executed”)
Output:
In python, we have one more conditional statement called elif statements. Elif
statement is used to check multiple conditions only if the given if condition false.
It's similar to an if-else statement and the only difference is that in else we will not
check the condition but in elif we will do check the condition.
Elif statements are similar to if-else statements but elif statements evaluate
multiple conditions.
Syntax:
if (condition):
elif (condition):
else:
#Set of statement to be executed when both if and elif conditions are false
Example: 1
if(a>0):
print("number is +ve")
40
elif(a==0):
else:
print("number is -ve")
Nested if Syntax:
if(condition):
if(condition):
#end of nested if
#end of if
The above syntax clearly says that the if block will contain another if block in it
and so on. If block can contain ‘n' number of if block inside it.
example
41
if(a==1):
print("today is sunday")
if(a==2):
print("today is monday")
if(a==3):
print("today is tuesday")
if(a==4):
print("today is wednesday")
if(a==5):
print("today is thursday")
if(a==6):
print("today is friday")
if(a==7):
print("today is saturday")
We have seen about the elif statements but what is this elif ladder. As the name
itself suggests a program which contains ladder of elif statements or elif statements
which are structured in the form of a ladder.
Syntax:
if (condition):
42
elif (condition):
#Set of statements to be executed when if condition is false and elif condition is true
elif (condition):
#Set of statements to be executed when both if and first elif condition is false and second elif
condition is true
elif (condition):
#Set of statements to be executed when if, first elif and second elif conditions are false and third
elif statement is true
else:
#Set of statement to be executed when all if and elif conditions are false
Example: 1
example
if(a==1):
print("today is sunday")
elif(a==2):
print("today is monday")
elif(a==3):
print("today is tuesday")
elif(a==4):
print("today is wednesday")
elif(a==5):
print("today is thursday")
43
elif(a==6):
print("today is friday")
elif(a==7):
print("today is saturday")
While loop
For loop
We use while loop when we don’t know the number of times to iterate.
3 parts of loop
3.increment /decrement
Syntax:
44
In while loop, we check the expression, if the expression becomes true, only then
the block of statements present inside the while loop will be executed. For every
iteration, it will check the condition and execute the block of statements until the
condition becomes false.
i=0
while (i<=10):
print(i)
i = i+1
print(“end loop)
Output:
1 2 3 4 5 6 7 8 9 10
For loop in python is used to execute a block of statements or code several times
until the given condition becomes false.
Syntax:
Here var will take the value from the sequence and execute it until all the values in
the sequence are done.
45
for lang in language:
Output:
Example
for i in range(1,11):
Print(i)
output
1 2 3 4 5 6 7 8 9 10
The break is a keyword in python which is used to bring the program control
out of the loop. The break statement breaks the loops one by one, i.e., in the
case of nested loops, it breaks the inner loop first and then proceeds to outer
loops. In other words, we can say that break is used to abort the current
execution of the program and the control goes to the next line after the loop.
The break is commonly used in the cases where we need to break the loop for a
given condition.
#loop statements
break;
46
example
for i in range(1,11):
if i==5:
break;
print(i);
output
1234
The continue statement in python is used to bring the program control to the
beginning of the loop. The continue statement skips the remaining lines of code
inside the loop and start with the next iteration. It is mainly used for a particular
condition inside the loop so that we can skip some specific code for a particular
condition.
#loop statements
continue;
Example
for i in range(1,11):
47
if i==5:
continue;
print(i);
Output:
10
In Python programming, a list is created by placing all the items (elements) inside
a square bracket [ ], separated by commas.
It can have any number of items and they may be of different types (integer, float,
string etc.).
1. # empty list
2. my_list = []
3. # list of integers
48
4. my_list = [1, 2, 3]
Also, a list can even have another list as an item. This is called nested list.
# nested list
my_list = ['p','r','o','b','e']
# Output: p
print(my_list[0])
# Output: o
print(my_list[2])
# Output: e
print(my_list[4])
Python provides the following built-in functions which can be used with the lists.
49
SN Function Description
a=[1,2,3]
a.append(4)
print(a)
a=[1,2,3]
a.clear()
print(a)
a=[1,2,3]
b=a.copy()
print(b)
a=[1,2,3,4,5,2,5,6]
Print(a.count(5))
50
List1=[1,2,3]
List2=[4,5,6]
List1.extend(List2)
Print(List1)
l=[1,2,3,4,5]
print(l.index(5))
L=[1,2,4,5]
L.insert(2,3)
Print(L)
int(S.pop())
print(S)
L=[1,2,1,1,3]
L.remove(1)
Print(L)
51
10 list.reverse() It reverses the list.
List=[1,2,3,4,5]
List.reverse()
Print(List)
3.Python Tuple
A tuple in Python is similar to a list. The difference between the two is that we
cannot change the elements of a tuple once it is assigned whereas, in a list,
elements can be changed.
Creating a Tuple
A tuple is created by placing all the items (elements) inside parentheses (),
separated by commas. The parentheses are optional, however, it is a good practice
to use them.
A tuple can have any number of items and they may be of different types (integer,
float, list, string, etc.).
# Empty tuple
my_tuple = ()
print(my_tuple) # Output: ()
# nested tuple
print(my_tuple)
A tuple can also be created without using parentheses. This is known as tuple
packing.for example
SN Function Description
53
print cmp(tuple1, tuple2)
list1= [ 1, 2, 3, 4 ]
tuple2 = tuple(list1)
54
print(tuple2)
The operators like concatenation (+), repetition (*), Membership (in) works in the
same way as they work with the list. Consider the following table for more detail.
Print(T1)
T1=T1+(10,)
Print(T1)
Iteration The for loop is used to iterate over the tuple T1=(1,2,3)
elements.
for i in T1:
print(i)
55
Output
len(T1) = 5
List VS Tuple
SN List Tuple
1 The literal syntax of list is shown The literal syntax of the tuple is shown
by the []. by the ().
3 The List has the variable length. The tuple has the fixed length.
5 The list Is used in the scenario in The tuple is used in the cases where we
which we need to store the simple need to store the read-only collections
56
collections with no constraints i.e., the value of the items can not be
where the value of the items can be changed. It can be used as the key
changed. inside the dictionary.
6 Syntax
7. Example
Python Sets
However, the set itself is mutable. We can add or remove items from it.
Sets can be used to perform mathematical set operations like union, intersection,
symmetric difference etc.
A set is created by placing all the items (elements) inside curly braces {}, separated
by comma or by using the built-in function set().
2. print(Days)
3. print(type(Days))
5. for i in Days:
6. print(i)
57
Output:
Friday
Tuesday
Monday
Saturday
Thursday
Sunday
Wednesday
2. print(Days)
3. print(type(Days))
5. for i in Days:
6. print(i)
Output:
Friday
58
Tuesday
Monday
Saturday
Thursday
Sunday
Wednesday
In the previous example, we have discussed about how the set is created in python.
However, we can perform various mathematical operations on python sets like
union, intersection, difference, etc.
The union of two sets are calculated by using the or (|) operator. The union of the
two sets contains the all the items that are present in both the sets.
1. Days1 = {"Monday","Tuesday","Wednesday","Thursday"}
2. Days2 = {"Friday","Saturday","Sunday"}
Output:
Python also provides the union() method which can also be used to calculate the
union of two sets. Consider the following example.
1. Days1 = {"Monday","Tuesday","Wednesday","Thursday"}
59
2. Days2 = {"Friday","Saturday","Sunday"}
Output:
The & (intersection) operator is used to calculate the intersection of the two sets in
python. The intersection of the two sets are given as the set of the elements that
common in both sets.
Output:
{'Martin', 'David'}
Output:
{'Martin', 'David'}
The intersection_update() method removes the items from the original set that are
not present in both the sets (all the sets if more than one are specified).
60
The Intersection_update() method is different from intersection() method since it
modifies the original set by removing the unwanted items, on the other hand,
intersection() method returns a new set.
4.
5. a.intersection_update(b, c)
6.
7. print(a)
Output:
{'castle'}
SN Method Description
# adding 's'
GEEK.add('s')
61
print('Letters are:', GEEK)
set1 = {1,2,3,4,5,6}
set1.clear()
print(set1)
set1 = {1, 2, 3, 4}
set2 = set1.copy()
print(set2)
4 difference_update(....) It modifies this set by removing all the items that are also
present in the specified sets.
result = A.symmetric_difference_update(B)
print('A = ', A)
print('B = ', B)
62
5 discard(item) It removes the specified item from the set.
fruits.discard("banana")
print(fruits)
6 intersection() It returns a new set that contains only the common elements
of both the sets. (all the sets if more than two are specified).
z = x.intersection(y)
print(z)
Python String
Till now, we have discussed numbers as the standard data types in python. In this
section of the tutorial, we will discuss the most popular data type in python i.e.,
string.
63
In python, strings are treated as the sequence of strings which means that python
doesn't support the character data type instead a single character written as 'p' is
treated as the string of length 1.
Like other languages, the indexing of the python strings starts from 0. For
example, The string "HELLO" is indexed as given in the below figure.
Python provides various in-built functions that are used for string handling. Many
String fun
Method Description
64
string = "python is AWesome."
b = string.capitalize()
print('Capitalized String:', b)
center(width It returns a space padded string with the original string centred with
,fillchar) equal number of left and right spaces.
new_string = string.center(24)
65
upper() The string upper() method converts all lowercase characters in a
string into uppercase characters and returns it.
print(string.upper())
split() The split() method breaks up a string at the specified separator and
returns a list of strings.
print(text.split( ))
replace() The replace() method returns a copy of the string where all
occurrences of a substring is replaced with another substring.
print(song.replace('cold', 'hurt'))
Index() The index() method returns the index number of given string (if
found).
66
sentence = 'Python'
result = sentence.index('n')
endswith() The endswith() method returns True if a string ends with the
specified suffix. If not, it returns False.
# returns False
print(result)
String Operators
Operator Description
67
1. str = "Hello"
3. print(str+str1)
1. print(str[4]) # prints o
[:] It is known as range slice operator. It is used to access the characters from
the specified range.
1. print(str[2:4]); # prints ll
Dictionary
68
Python dictionary is an unordered collection of items. While other compound
data types have only value as an element, a dictionary has a key: value pair.
Dictionaries are optimized to retrieve values when the key is known.
An item has a key and the corresponding value expressed as a pair, key: value.
Method Description
car.clear()
print(car)
69
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.copy()
print(x)
x = car.get("model")
print(x)
70
items() Returns a list containing a tuple for each key value
pair
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.items()
print(x)
x = car.keys()
print(x)
71
"year": 1964
}
car.pop("model")
print(car)
car.popitem()
print(car)
72
}
x = car.setdefault("model", "Bronco")
print(x)
73
}
x = car.values()
print(x)
74
Unit-3
75
Python Functions
Functions are the most important aspect of an application. A function can be
defined as the organized block of reusable code which can be called
whenever required.
Python allows us to divide a large program into the basic building blocks
known as function. The function contains the set of programming statements
enclosed by {}. A function can be called multiple times to provide reusability
and modularity to the python program.
1.Inbuilt functions
The user can create its functions which can be called user-defined functions.
o We can call python functions any number of times in a program and from
any place in a program.
o We can track a large python program easily when it is divided into multiple
functions.
76
o Reusability is the main achievement of python functions.
Creating a function
In python, we can use def keyword to define the function. The syntax to define a
function in python is given below.
1. def my_function():
2. function-suite
3. <expression>
The function block is started with the colon (:) and all the same level block
statements remain at the same indentation.
A function can accept any number of parameters that must be the same in the
definition and function calling.
Function calling
In python, a function must be defined before the function calling otherwise the
python interpreter gives an error. Once the function is defined, we can call it from
another function or the python prompt. To call the function, use the function name
followed by the parentheses.
A simple function that prints the message "Hello Word" is given below.
1. def hello_world():
77
2. print("hello world")
3.
4. hello_world()
Output:
hello world
The information into the functions can be passed as the parameters. The parameters
are specified in the parentheses. We can give any number of parameters, but we
have to separate them with a comma.
Creating a function
In python, we can use def keyword to define the function. The syntax to define a
function in python is given below.
1. def my_function(parameterlist):
2. function-suite
3. <expression>
The function block is started with the colon (:) and all the same level block
statements remain at the same indentation.
A function can accept any number of parameters that must be the same in the
definition and function calling.
Function calling
In python, a function must be defined before the function calling otherwise the
python interpreter gives an error. Once the function is defined, we can call it from
another function or the python prompt. To call the function, use the function name
followed by the parentheses.
78
Consider the following example which contains a function that accepts a string as
the parameter and prints it.
Example
4. c=a+b;
5. Print(“sum is”,c)
7. a = int(input("Enter a: "))
8. b = int(input("Enter b: "))
9. sum(a,b)
Output:
Enter a: 10
Enter b: 20
Sum = 30
Creating a function
In python, we can use def keyword to define the function. The syntax to define a
function in python is given below.
1. def my_function():
79
2. function-suite
3. Return <expression>
The function block is started with the colon (:) and all the same level block
statements remain at the same indentation.
A function can accept any number of parameters that must be the same in the
definition and function calling.
Function calling
In python, a function must be defined before the function calling otherwise the
python interpreter gives an error. Once the function is defined, we can call it from
another function or the python prompt. To call the function, use the function name
followed by the parentheses.
A return statement is used to end the execution of the function call and “returns”
the result (value of the expression following the return keyword) to the caller. The
statements after the return statements are not executed. If the return statement is
without any expression, then the special value None is returned.
z = (x + y)
return z
a=4
b=7
80
res2 = f(a, b)
In the event that you pass arguments like whole numbers, strings or tuples to a
function, the passing is like call-by-value because you can not change the value of
the immutable objects being passed to the function.
# call by value
string = "hello"
def test(string):
string = "world"
test(string)
Output
In python, all the functions are called by reference, i.e., all the changes made to the
reference inside the function revert back to the original value referred by the
reference.
However, there is an exception in the case of mutable objects since the changes
made to the mutable objects like string do not revert to the original string rather, a
new string object is made, and therefore the two different objects are printed.
list1=[1,2,3,4,5]
def fun(list1):
list1.append(20)
fun(list1)
print("outside",list1)
Output:
82
Scope of variables
The scopes of the variables depend upon the location where the variable is being
declared. The variable declared in one part of the program may not be accessible to
the other parts.
In python, the variables are defined with the two types of scopes.
83
Parameter Local Global
inside a function in which they
are declared.
It is stored on the stack unless It is stored on a fixed location
Memory storage
specified. decided by the compiler.
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.
def calc_factorial(x):
if x == 1:
return 1
else:
return (x * calc_factorial(x-1))
num = 4
Output
84
The factorial of 4 is 24
Advantages of Recursion
Disadvantages of Recursion
85
Python Modules
A python module can be defined as a python program file which contains a
python code including python functions, class, or variables. In other words,
we can say that our python code file saved with the extension (.py) is treated
as the module. We may have a runnable code inside the python module.
Modules in Python provides us the flexibility to organize the code in a logical way.
To use the functionality of one module into another, we must have to import the
specific module.
Example
def displayMsg(name)
print("Hi "+name);
Here, we need to include this module into our main module to call the method
displayMsg() defined in the module named file.
We need to load the module in our python code to use its functionality. Python
provides two types of statements as defined below.
The import statement is used to import all the functionality of one module into
another. Here, we must notice that we can use the functionality of any python
source file by importing that file as the module into another python source file.
86
We can import multiple modules with a single import statement, but a module is
loaded once regardless of the number of times, it has been imported into our file.
Hence, if we need to call the function displayMsg() defined in the file file.py, we
have to import that file as a module into our module as shown in the example
below.
Example:
import file;
file.displayMsg(name)
Output:
Hi John
Instead of importing the whole module into the namespace, python provides the
flexibility to import only the specific attributes of a module. This can be done by
using from? import statement. The syntax to use the from-import statement is
given below.
calculation.py:
2. def summation(a,b):
87
3. return a+b
4. def multiplication(a,b):
5. return a*b;
6. def divide(a,b):
7. return a/b;
Main.py:
5. print("Sum = ",summation(a,b))
6. Output:
Sum = 30
Renaming a module
Python provides us the flexibility to import some module with a specific name so
that we can use this name to use that module in our python source file.
88
import <module-name> as <specific-name>
Example
a = int(input("Enter a?"));
b = int(input("Enter b?"));
print("Sum = ",cal.summation(a,b))
Output:
Enter a?10
Enter b?20
Sum = 30
The dir() function returns a sorted list of names defined in the passed module. This
list contains all the sub-modules, variables and functions defined in this module.
Example
1. import json
2.
3. List = dir(json)
4.
5. print(List)
Output:
89
'__file__', '__loader__', '__name__', '__package__', '__path__', '__spec__',
'__version__',
As we have already stated that, a module is loaded once regardless of the number
of times it is imported into the python source file. However, if you want to reload
the already imported module to re-execute the top-level code, python provides us
the reload() function. The syntax to use the reload() function is given below.
1. reload(<module-name>)
for example, to reload the module calculation defined in the previous example, we
must use the following line of code.
1. reload(calculation)
Statistics Module
Math Module
This module, as mentioned in the Python 3's documentation, provides access to the
mathematical functions defined by the C standard.
Random module
90
Create and Access a Python Package
Packages are a way of structuring many packages and modules which helps in a
well-organized hierarchy of data set, making the directories and modules easy to
access.
3. Finally we create an __init__.py file inside the directory, to let Python know
that the directory is a package.
Let’s look at this example and see how a package is created. Let’s create a package
named Cars and build three modules in it namely, Bmw, Audi and Nissan.
class Bmw:
91
# First we create a constructor for this class
def __init__(self):
def outModels(self):
Then we create another file with the name Audi.py and add the similar type of
code to it with different members.
def add(x,y):
z=x*y
return(z)
3. Finally we create the __init__.py file. This file will be placed inside Cars
directory and can be left blank or we can put this initialisation code into it.
print(b.add(x,y))
Now, let’s use the package that we created. To do this make a sample.py file in the
same directory where Cars package is located and add the following code to it:
92
# Import classes from your brand new package
ModBMW = Bmw()
ModBMW.outModels()
ModAudi = Audi()
ModAudi.outModels()
93
Unit-4
Exception Handling
An exception is an error that happens during execution of a program. When that
error occurs, Python generate an exception that can be handled, which avoids your
program to crash.
Exceptions are convenient in many ways for handling errors and special conditions
in a program. When you think that you have a code which can produce an error then
Types of Exception
1)Build in
2) User Define
1)Build in Exception
94
IOError
ImportError
ValueError
Raised when a built-in operation or function receives an argument that has the
KeyboardInterrupt
Raised when the user hits the interrupt key (normally Control-C or Delete)
EOFError
Syntax
try:
except:
exception handling
95
Example user define
try:
print (1/0)
except ZeroDivisionError:
Output
Build in
... try:
... break
96
File Handling
File handling in Python requires no importing of modules.
File Object
Instead we can use the built-in object "file". That object provides basic functions
and methods necessary to manipulate files by default. Before you can read, append
or write to a file, you will first have to it using
The open() function is used to open files in our system, the filename is the
The mode indicates, how the file is going to be opened "r" for reading,"w" for
writing and "a" for a appending. The open function takes two arguments, the name
of the file and and the mode or which we would like to open the file. By default,
when only the filename is passed, the open function opens the file in read mode.
Example
This small script, will open the (hello.txt) and print the content.
This will store the file information in the file object "filename".
filename = "hello.txt"
print line,
2.Read ()
97
read() #return one big string
3.Write ()
4.Append ()
The append function is used to append to the file instead of overwriting it.
To append to an existing file, simply open the file in append mode ("a"):
5.Close()When you’re done with a file, use close() to close it and free up any
system
6.seek() sets the file's current position at the offset. The whence argument is
optional and defaults to 0, which means absolute file positioning, other values are 1
which means seek relative to the current position and 2 means seek relative to the
file's end.
7.tell() Python file method tell() returns the current position of the file read/write
pointer within the file.
fh = open("hello.txt", "r")
print fh.read()
fh = open("hello".txt", "r")
print fh.readline()
fh = open("hello.txt.", "r")
print fh.readlines()
fh = open("hello.txt","w")
write("Hello World")
fh.close()
fh = open("hello.txt", "w")
lines_of_text = ["a line of text", "another line of text", "a third line"]
fh.writelines(lines_of_text)
fh.close()
99
fh = open("Hello.txt", "a")
fh.close()
fh = open("hello.txt", "r")
print fh.read()
fh.close()
To use this module you need to import it first and then you can call any related
functions.
The rename() method takes two arguments, the current filename and the new
filename.
Syntax
os.rename(current_file_name, new_file_name)
Example
#!/usr/bin/python
import os
100
9.The remove() Method
You can use the remove() method to delete files by supplying the name of the file
to be deleted as the argument.
Syntax
os.remove(file_name)
Example
#!/usr/bin/python
import os
os.remove("text2.txt")
4. enumerate() – Returns an enumerate object for the passed iterable that can
be used to iterate over the items of iterable with an access to their indexes.
101
5. list() – It is used to create a list by using an existing iterable(list, tuple,
dictionary, set).
7. isfile() – It checks whether the passed parameter denotes the path to a file. If
yes then returns True otherwise False
1.Class
We can think of class as a sketch of a parrot with labels. It contains all the details
about the name, colors, size etc. Based on these descriptions, we can study about
the parrot. Here, a parrot is an object.
class Parrot:
pass
2.Object
102
An object (instance) is an instantiation of a class. When class is defined, only the
description for the object is defined. Therefore, no memory or storage is allocated.
obj = Parrot()
3.Methods
Methods are functions defined inside the body of a class. They are used to define
the behaviors of an object.
4.Inheritance
Inheritance is a way of creating a new class for using details of an existing class
without modifying it. The newly formed class is a derived class (or child class).
Similarly, the existing class is a base class (or parent class).
5.Encapsulation
Using OOP in Python, we can restrict access to methods and variables. This
prevents data from direct modification which is called encapsulation. In Python,
we denote private attributes using underscore as the prefix i.e single _ or
double __.
6.Polymorphism
Polymorphism is an ability (in OOP) to use a common interface for multiple forms
(data types).
Suppose, we need to color a shape, there are multiple shape options (rectangle,
square, circle). However we could use the same method to color any shape. This
concept is called Polymorphism.
7.Data Abstraction
Data abstraction and encapsulation both are often used as synonyms. Both are
nearly synonyms because data abstraction is achieved through encapsulation.
103
Abstraction is used to hide internal details and show only functionalities.
Abstracting something means to give names to things so that the name captures the
core of what a function or a whole program does.
Python Classes/Objects
Python is an object oriented programming language.
Create a Class
Example
class MyClass:
x=5
Example
p1 = MyClass()
print(p1.x)
104
Example
p1.age = 40
Example
class Person:
def myfunc(self):
print("Hello my name is " + self.name)
p1 = Person("John", 36)
p1.myfunc()
Output:
my age is 36
Attribute Description
105
__dict__ This is a dictionary holding the class namespace.
class Employee:
empCount = 0
self.name = name
self.salary = salary
Employee.empCount += 1
def displayCount(self):
def displayEmployee(self):
106
print "Name : ", self.name, ", Salary: ", self.salary
Output
Python’s memory allocation and deallocation method is automatic. The user does
not have to preallocate or deallocate memory similar to using dynamic memory
allocation in languages such as C or C++.
Python uses two strategies for memory allocation:
Reference counting
Garbage collection
107
Destroying objects.
Example
This __del__() destructor prints the class name of an instance that is about to be
destroyed −
https://www.javatpoint.com/python-modules
https://www.tutorialspoint.com/execute_python_online.php
https://www.onlinegdb.com/online_python_compiler
108