Programming in Python Notes
Programming in Python Notes
3 Semester, BCA
CLASS:BCA3rdSem
Unit-I
6-34
Operators and Expressions: Operators in Python,
Expressions, Precedence, Associativity of Operators,
Non Associative Operators.
Unit-II
Unit-IV
Exception Handling: Exceptions, Built-in exceptions,
Exception handling, User defined exceptions in
Python.
Unit- 1
What is Python?
Python is a popular programming language. It was created by Guido van Rossum, and released in
1991.
It is used for:
web development (server-side),
software development,
mathematics,
system scripting.
What can Python do?
Python can be used on a server to create web applications.
Python can be used alongside software to create workflows.
Python can connect to database systems. It can also read and modify files.
Python can be used to handle big data and perform complex mathematics.
Python can be used for rapid prototyping, or for production-ready software development.
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.
Python Features
Python provides lots of features that are listed below.
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.
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.
10) Integrated
It can be easily integrated with languages like C, C++, JAVA etc.
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 .
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:
In the System variable window, find the Path variable and click Edit:
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:
C:>python –version
Python 3.4.3
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”.
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.
Step 7) You can see the output of your program at the bottom of the screen.
If the help function is passed without an argument, then the interactive help utility starts up on the
console.
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
Most of the programming languages like C, C++, Java use braces { } to define a block of code.
Python uses indentation.
A code block (body of a function, loop etc.) starts with indentation and ends with the first
unindented line. The amount of indentation is up to you, but it must be consistent throughout that
block.
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.
It extends up to the newline character. Comments are for programmers for better understanding of
a program. Python Interpreter ignores comment.
For Example
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.
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
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.
1. number = 10
print (a)
print (b)
print (c)
Constants
A constant is a type of variable whose value cannot be changed. It is helpful to think of constants
as containers that hold information which cannot be changed later.types
(int,float,double,char,strings)
1. PI = 3.14
2. GRAVITY = 9.8
Create a main.py
1. import constant
2. print(constant.PI)
3. print(constant.GRAVITY)
When you run the program, the output will be:
3.14
9.8
Data Type in Python
1. Number Data Type in Python
Python supports integers, floating point numbers and complex numbers. They are defined as int,
float and complex class 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. 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
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.).
# Tuple having integers
print(my_tuple)
# Output:
(1, 2, 3,4)
4.Python Strings
A string is a sequence of characters. A character is simply a symbol. Strings can be created by
enclosing characters inside a single quote or double quotes. Even triple quotes can be used in
Python but generally used to represent multiline strings and docstrings.
# all of the following are equivalent
my_string = ‘Hello’
print(my_string)
print(my_string)
5.Python Sets
A set is an unordered collection of items. Every element is unique (no duplicates) and must be
immutable (which cannot be changed).
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
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.
Creating a dictionary is as simple as placing items inside curly braces {} separated by comma.
An item has a key and the corresponding value expressed as a pair, key: value.
my_dict = {1: ‘apple’, 2: ‘ball’}
# initializing string
s = “10010”
s = “10010”
c = int(s)
print (c)
e = float(s)
print (e)
Output:
We can also output data to a file, but this will be discussed later. An example use is given below.
a=5
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])
c=a+b
print(c)
Python Import
A module is a file containing Python definitions and statements. Python modules have a filename
and end with the extension .py.
Definitions inside a module can be imported to another module or the interactive interpreter in
Python. We use the import keyword to do this.
For example, we can import the math module by typing in import math.
import math
r=int(input(“enter the radius”))
area=(math.pi)*r*r;
print(area)output:
3.141592653589793
Operators in Python
Operators are used to perform operations on variables and values.
Python divides the operators in the following groups:
Arithmetic operators
Assignment operators
Comparison operators
Logical operators
Identity operators
Membership operators
Bitwise operators
!= Not equal x != y
> Greater than x>y
< Less than x<y
>= Greater than or equal to x >= y
<= Less than or equal to x <= y
Returns True if a
in x in y
sequence with the
specified value is
present in the object
Returns True if a
sequence with the
not in x not in y
specified value is not
present in the 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.
1. List comprehension
The syntax for list comprehension is shown below:
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
The syntax for generator expression is shown below:
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
You can use the following construct for one-liner conditions:
Example:
>>> x = “1” if True else “2”
>>> x
‘1’
Precedence Order
When two operators share an operand, the operator with the higher precedence goes first. For
example, since multiplication has a higher precedence than addition, a + b * c is treated as a + (b
* c), and a * b + c is treated as (a * b) + c.(BODMAS)
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.
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.
Unit-2
Control Structures
Types
1.Decision Making Statements
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:
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
2 If(Num < 10):
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
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
2 if(num > 10):
Elif statements are similar to if-else statements but elif statements evaluate multiple conditions.
Syntax:
if (condition):
elif (condition):
#Set of statements to be executed when if condition is false and elif condition is true
else:
#Set of statement to be executed when both if and elif conditions are false
Example: 1
a=int(input(“enter the number to find +ve or -ve or whole number”))
if(a>0):
print(“number is +ve”)
elif(a==0):
print(“number is -ve”)
#4) Nested if/ladder statements
Nested if-else statements mean that an if statement or if-else statement is present inside another if
or if-else block. Python provides this feature as well, this in turn will help us to check multiple
conditions in a given program.
An if statement present inside another if statement which is present inside another if statements
and so on.
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
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”)
Syntax:
if (condition):
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”)
elif(a==6):
print(“today is friday”)
elif(a==7):
print(“today is saturday”)
We use while loop when we don’t know the number of times to iterate.
3 parts of loop
1.intialization (Starting point)
2.condition (ending point)
3.increment /decrement
Syntax:
while (expression): block of statements Increment or decrement operator
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
Syntax:
for var in sequence: Block of code
Here var will take the value from the sequence and execute it until all the values in the sequence
are done.
Example
for i in range(1,11):
Print(i)
output
1 2 3 4 5 6 7 8 9 10
Python break statement
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;
example
for i in range(1,11):
if i==5:
break;
print(i);
output
1234
#loop statements
continue;
#the code to be skipped
Example
i=1; #initializing a local variable
for i in range(1,11):
if i==5:
continue;
print(i);
Output:
1
10
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
4. my_list = [1, 2, 3]
# nested list
# Output: p
print(my_list[0])
# Output: o
print(my_list[2])
# Output: e
print(my_list[4])
SN Function Description
The element represented by the object obj
is added to the list.
a=[1,2,3]
1 list.append(obj) a.append(4)
print(a)
It removes all the elements from the list.
a=[1,2,3]
2 list.clear() a.clear()
print(a)
3 List.copy() b=a.copy()
print(b)
List2=[4,5,6]
5 list.extend(seq)
List1.extend(List2)
Print(List1)
print(S)
9 list.remove(obj) L.remove(1)
Print(L)
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: ()
my_tuple = (1, 2, 3)
# nested tuple
print(my_tuple)
A tuple can also be created without using parentheses. This is known as tuple packing.for
example
print(tuple2)
Basic Tuple operations
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.
T1= (1, 2, 3, 4, 5,
6, 7, 8, 9)
It concatenates the tuple T1=T1+(10,)
Concatenation mentioned on either side of the
operator.
Print(T1)
print(i)
Output
1
The for loop is used to iterate
Iteration 2
over the tuple elements.
T1=(1,2,3,4,5)
It is used to get the length of
Length
the tuple.
len(T1) = 5
List VS Tuple
SN List Tuple
The literal syntax of list is The literal syntax of the tuple is
1
shown by the []. shown by the ().
2 The List is mutable. The tuple is immutable.
The List has the variable
3 The tuple has the fixed length.
length.
The list provides more The tuple provides less
4
functionality than tuple. functionality than the list.
The list Is used in the The tuple is used in the cases
scenario in which we need where we need to store the
to store the simple read-only collections i.e., the
5
collections with no value of the items can not be
constraints where the value changed. It can be used as the
of the items can be changed. key inside the dictionary.
6 Syntax
7. Example
Python Sets
A set is an unordered collection of items. Every element is unique (no duplicates) and must be
immutable (which cannot be changed).
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().
Output:
looping through the set elements …
Friday
Tuesday
Monday
Saturday
Thursday
Sunday
Wednesday
Output:
looping through the set elements …
Friday
Tuesday
Monday
Saturday
Thursday
Sunday
Wednesday
1. Days1 = {“Monday”,”Tuesday”,”Wednesday”,”Thursday”}
2. Days2 = {“Friday”,”Saturday”,”Sunday”}
3. print(Days1|Days2) #printing the union of the sets
Output:
{‘Friday’, ‘Sunday’, ‘Saturday’, ‘Tuesday’, ‘Wednesday’, ‘Monday’, ‘Thursday’}
Python also provides the union() method which can also be used to calculate the union of two
sets. Consider the following example.
Example 2: using union() method
1. Days1 = {“Monday”,”Tuesday”,”Wednesday”,”Thursday”}
2. Days2 = {“Friday”,”Saturday”,”Sunday”}
3. print(Days1.union(Days2)) #printing the union of the sets
Output:
{‘Friday’, ‘Monday’, ‘Tuesday’, ‘Thursday’, ‘Wednesday’, ‘Sunday’, ‘Saturday’}
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.
SN Method Description
It adds an item to the set. It has no
effect if the item is already present in
the set.
GEEK = {‘g’, ‘e’, ‘k’}
1 add(item)
# adding ‘s’
GEEK.add(‘s’)
set1.clear()
2 clear()
print(“\nSet after using clear()
function”)
print(set1)
print(set2)
result =
4 difference_update(….) A.symmetric_difference_update(B)
print(‘A = ‘, A)
print(‘B = ‘, B)
print(‘result = ‘, result)
print(fruits)
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.
In python, strings can be created by enclosing the character or the sequence of characters in the
quotes. Python allows us to use single quotes, double quotes, or triple quotes to create the
string.
Consider the following example in python to create a string.
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.
Method Description
It capitalizes the first character of the String. This
capitalize()
function is deprecated in python3
string = “python is AWesome.”
b = string.capitalize()
print(‘New String: ‘, b)
print(‘Capitalized String:’, b)
casefold()
center(width
,fillchar) new_string = string.center(24)
print(song.replace(‘cold’, ‘hurt’))
Index()
result = sentence.index(‘n’)
endswith()
# returns False
print(result)
String Operators
Operator Description
It is known as concatenation operator used to join the
strings given either side of the operator.
1. str = “Hello”
+ 2. str1 = ” world”
3. print(str+str1)
# prints Hello world
Dictionary
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.
# dictionary with integer keys
my_dict = {1: ‘apple’, 2: ‘ball’}
Python has a set of built-in methods that you can use on dictionaries.
Method Description
Removes all the elements from the dictionary
car = {
“brand”: “Ford”,
“model”: “Mustang”,
“year”: 1964
clear() }
car.clear()
print(car)
print(x)
fromkeys() y = 0
thisdict = dict.fromkeys(x, y)
print(thisdict)
print(x)
“brand”: “Ford”,
“model”: “Mustang”,
x = car.items()
print(x)
print(x)
print(car)
print(car)
“brand”: “Ford”,
“model”: “Mustang”,
“year”: 1964
setdefault() }
x = car.setdefault(“model”, “Bronco”)
print(x)
“brand”: “Ford”,
“model”: “Mustang”,
update()
“year”: 1964
car.update({“color”: “White”})
car.update({“age”:34})
print(car)
“brand”: “Ford”,
“model”: “Mustang”,
“year”: 1964
values() }
x = car.values()
print(x)
Unit-3
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.
Types of functions in python
1.Inbuilt functions
Python provide us various inbuilt functions like range() or print(),input().
By using functions, we can avoid rewriting same logic/code again and again in a program.
We can call python functions any number of times in a program and from any place in a
program.
We can track a large python program easily when it is divided into multiple functions.
Reusability is the main achievement of python functions.
Improving clarity of the code
Information hiding
Reducing duplication of code
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. defhello_world():
2. print(“hello world”)
3.
4. hello_world()
Output:
hello world
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. defmy_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.
Consider the following example which contains a function that accepts a string as the parameter
and prints it.
Example
Output:
Enter a: 10
Enter b: 20
Sum = 30
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
res2 = f(a, b)
# call by value
string = “hello”
def test(string):
string = “world”
test(string)
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:
(‘inside the list’, [1, 2, 3, 4, 5, 20])
In python, the variables are defined with the two types of scopes.
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
The factorial of 4 is 24
Advantages of Recursion
1. Recursive functions make the code look clean and elegant.
2. A complex task can be broken down into simpler sub-problems using recursion.
3. Sequence generation is easier with recursion than using some nested iteration.
Disadvantages of Recursion
1. Sometimes the logic behind recursion is hard to follow through.
2. Recursive calls are expensive (inefficient) as they take up a lot of memory and time.
3. Recursive functions are hard to debug.
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
In this example, we will create a module named as file.py which contains a function func that
contains a code to print some message on the console.
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.
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.
Example:
import file;
name = input(“Enter the name?”)
file.displayMsg(name)
Output:
Enter the name?John
Hi John
calculation.py:
1. #place the code in the calculation.py
2. defsummation(a,b):
3. return a+b
4. defmultiplication(a,b):
5. return a*b;
6. defdivide(a,b):
7. return a/b;
Main.py:
1. fromcalculation import summation
2. #it will import only the summation() from calculation.py
3. a = int(input(“Enter the first number”))
4. b = int(input(“Enter the second number”))
5. print(“Sum = “,summation(a,b))
6. Output:
Enter the first number10
Sum = 30
The from…import statement is always better to use if we know the attributes to be imported
from the module in advance. It doesn’t let our code to be heavier. We can also import all the
attributes from a module by using *.
Consider the following syntax.
1. from<module> import *
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.
#the module calculation of previous example is imported in this example as cal. import calculatio
n as cal;
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
Example
1. importjson
2.
3. List = dir(json)
4.
5. print(List)
Output:
[‘JSONDecoder’, ‘JSONEncoder’, ‘__all__’, ‘__author__’, ‘__builtins__’, ‘__cached__’,
‘__doc__’,
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)
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
This module, as mentioned in the Python 3’s documentation, implements pseudo-random number
generators for various distributions.
1. First, we create a directory and give it a package name, preferably related to its operation.
2. Then we put the classes and the required functions in it.
3. Finally we create an __init__.py file inside the directory, to let Python know that the directory is
a package.
Example of Creating 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.
def __init__(self):
def outModels(self):
print(‘\t%s ‘ % model)
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.
from cars import b
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:
ModBMW = Bmw()
ModBMW.outModels()
ModAudi = Audi()
ModAudi.outModels()
Unit-4
Exception Handling
An exception is an error that happens during execution of a
program. When that
program to crash.
in a program. When you think that you have a code which can
produce an error then
you can use exception handling.
Types of Exception
1)Build in
2) User Define
1)Build in Exception
Below is some common exceptions errors in Python:
IOError
If the file cannot be opened.
ImportError
If python cannot find the module
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
Raised when one of the built-in functions (input() or raw_input())
hits an
Syntax
try:
except:
exception handling
try:
print (1/0)
except ZeroDivisionError:
Output
Build in
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 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”
3.Write ()
This method writes a sequence of strings to the file.
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
resources taken up by the open file.
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.
File Handling Examples
print fh.read()
print fh.readline()
print fh.readlines()
write(“Hello World”)
fh.close()
To write to a file, use:
fh = open(“hello.txt”, “w”)
fh.writelines(lines_of_text)
fh.close()
fh.close()
print fh.read()
fh.close()
Python os module provides methods that help you perform file-processing operations, such as
renaming and deleting files.
To use this module you need to import it first and then you can call any related functions.
Syntax
os.rename(current_file_name, new_file_name)
Example
Following is the example to rename an existing file test1.txt −
#!/usr/bin/python
import os
Syntax
os.remove(file_name)
Example
Following is the example to delete an existing file test2.txt −
#!/usr/bin/python
import os
os.remove(“text2.txt”)
One of the popular approaches to solve a programming problem is by creating objects. This is
known as Object-Oriented Programming (OOP).
1.Class
A class is a blueprint for the object.
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
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.
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
To create a class, use the keyword class:
Example
class MyClass:
x=5
Create Object/Accessing members
Now we can use the class named MyClass to create objects:
Example
p1.age = 40
Example
Insert a function that prints a greeting, and execute it on the p1 object:
class Person:
p1 = Person(“John”, 36)
p1.myfunc()
Output:
my age is 36
Attribute Description
__dict__ This is a dictionary holding the class namespace.
This gives us the class documentation if
__doc__
documentation is present. None otherwise.
__name__ This gives us the class name.
This gives us the name of the module in which the
class is defined.
__module__ In an interactive mode it will give us __main__.
empCount = 0
self.name = name
self.salary = salary
Employee.empCount += 1
def displayCount(self):
def displayEmployee(self):
Output
Employee.__name__: Employee
Employee.__module__: __main__
Employee.__bases__: ()
Employee.__dict__: {‘__module__’: ‘__main__’, ‘displayCount’:
Destroying objects.
A class implements the special method __del__(), called a destructor, that is invoked when the
instance is about to be destroyed. This method might be used to clean up any non memory
resources used by an instance.
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
CLASS:BCA3rdSem
Batch: 2019-2021
Python
Notes as per IKGPTU Syllabus
Name of Faculty: Ms<Jatinderpal Kaur>
Faculty of IT Department, SBS College. Ludhiana
Unit-I
6-34
Operators and Expressions: Operators in Python,
Expressions, Precedence, Associativity of Operators,
Non Associative Operators.
Unit-II
Unit-IV
Exception Handling: Exceptions, Built-in exceptions,
Exception handling, User defined exceptions in
Python.
Unit- 1
What is Python?
Python is a popular programming language. It was created by Guido van Rossum, and released in
1991.
It is used for:
Python Features
Python provides lots of features that are listed below.
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.
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.
10) Integrated
It can be easily integrated with languages like C, C++, JAVA etc.
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 .
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:
In the System variable window, find the Path variable and click Edit:
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:
C:>python –version
Python 3.4.3
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”.
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.
Step 7) You can see the output of your program at the bottom of the screen.
If the help function is passed without an argument, then the interactive help utility starts up on the
console.
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
Most of the programming languages like C, C++, Java use braces { } to define a block of code.
Python uses indentation.
A code block (body of a function, loop etc.) starts with indentation and ends with the first
unindented line. The amount of indentation is up to you, but it must be consistent throughout that
block.
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.
It extends up to the newline character. Comments are for programmers for better understanding of
a program. Python Interpreter ignores comment.
For Example
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.
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
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.
1. number = 10
print (a)
print (b)
print (c)
Constants
A constant is a type of variable whose value cannot be changed. It is helpful to think of constants
as containers that hold information which cannot be changed later.types
(int,float,double,char,strings)
1. PI = 3.14
2. GRAVITY = 9.8
Create a main.py
1. import constant
2. print(constant.PI)
3. print(constant.GRAVITY)
When you run the program, the output will be:
3.14
9.8
Data Type in Python
1. Number Data Type in Python
Python supports integers, floating point numbers and complex numbers. They are defined as int,
float and complex class 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. 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
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.).
# Tuple having integers
print(my_tuple)
# Output:
(1, 2, 3,4)
4.Python Strings
A string is a sequence of characters. A character is simply a symbol. Strings can be created by
enclosing characters inside a single quote or double quotes. Even triple quotes can be used in
Python but generally used to represent multiline strings and docstrings.
# all of the following are equivalent
my_string = ‘Hello’
print(my_string)
print(my_string)
5.Python Sets
A set is an unordered collection of items. Every element is unique (no duplicates) and must be
immutable (which cannot be changed).
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
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.
Creating a dictionary is as simple as placing items inside curly braces {} separated by comma.
An item has a key and the corresponding value expressed as a pair, key: value.
my_dict = {1: ‘apple’, 2: ‘ball’}
# initializing string
s = “10010”
s = “10010”
c = int(s)
print (c)
e = float(s)
print (e)
Output:
We can also output data to a file, but this will be discussed later. An example use is given below.
a=5
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])
c=a+b
print(c)
Python Import
A module is a file containing Python definitions and statements. Python modules have a filename
and end with the extension .py.
Definitions inside a module can be imported to another module or the interactive interpreter in
Python. We use the import keyword to do this.
For example, we can import the math module by typing in import math.
import math
r=int(input(“enter the radius”))
area=(math.pi)*r*r;
print(area)output:
3.141592653589793
Operators in Python
Operators are used to perform operations on variables and values.
Python divides the operators in the following groups:
Arithmetic operators
Assignment operators
Comparison operators
Logical operators
Identity operators
Membership operators
Bitwise operators
!= Not equal x != y
> Greater than x>y
< Less than x<y
>= Greater than or equal to x >= y
<= Less than or equal to x <= y
Returns True if a
in x in y
sequence with the
specified value is
present in the object
Returns True if a
sequence with the
not in x not in y
specified value is not
present in the 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.
1. List comprehension
The syntax for list comprehension is shown below:
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
The syntax for generator expression is shown below:
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
You can use the following construct for one-liner conditions:
Example:
>>> x = “1” if True else “2”
>>> x
‘1’
Precedence Order
When two operators share an operand, the operator with the higher precedence goes first. For
example, since multiplication has a higher precedence than addition, a + b * c is treated as a + (b
* c), and a * b + c is treated as (a * b) + c.(BODMAS)
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.
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.
Unit-2
Control Structures
Types
1.Decision Making Statements
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:
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
2 If(Num < 10):
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
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
2 if(num > 10):
Elif statements are similar to if-else statements but elif statements evaluate multiple conditions.
Syntax:
if (condition):
elif (condition):
#Set of statements to be executed when if condition is false and elif condition is true
else:
#Set of statement to be executed when both if and elif conditions are false
Example: 1
a=int(input(“enter the number to find +ve or -ve or whole number”))
if(a>0):
print(“number is +ve”)
elif(a==0):
print(“number is -ve”)
#4) Nested if/ladder statements
Nested if-else statements mean that an if statement or if-else statement is present inside another if
or if-else block. Python provides this feature as well, this in turn will help us to check multiple
conditions in a given program.
An if statement present inside another if statement which is present inside another if statements
and so on.
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
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”)
Syntax:
if (condition):
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”)
elif(a==6):
print(“today is friday”)
elif(a==7):
print(“today is saturday”)
We use while loop when we don’t know the number of times to iterate.
3 parts of loop
1.intialization (Starting point)
2.condition (ending point)
3.increment /decrement
Syntax:
while (expression): block of statements Increment or decrement operator
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
Syntax:
for var in sequence: Block of code
Here var will take the value from the sequence and execute it until all the values in the sequence
are done.
Example
for i in range(1,11):
Print(i)
output
1 2 3 4 5 6 7 8 9 10
Python break statement
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;
example
for i in range(1,11):
if i==5:
break;
print(i);
output
1234
#loop statements
continue;
#the code to be skipped
Example
i=1; #initializing a local variable
for i in range(1,11):
if i==5:
continue;
print(i);
Output:
1
10
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
4. my_list = [1, 2, 3]
# nested list
# Output: p
print(my_list[0])
# Output: o
print(my_list[2])
# Output: e
print(my_list[4])
SN Function Description
The element represented by the object obj
is added to the list.
a=[1,2,3]
1 list.append(obj) a.append(4)
print(a)
It removes all the elements from the list.
a=[1,2,3]
2 list.clear() a.clear()
print(a)
3 List.copy() b=a.copy()
print(b)
List2=[4,5,6]
5 list.extend(seq)
List1.extend(List2)
Print(List1)
print(S)
9 list.remove(obj) L.remove(1)
Print(L)
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: ()
my_tuple = (1, 2, 3)
# nested tuple
print(my_tuple)
A tuple can also be created without using parentheses. This is known as tuple packing.for
example
print(tuple2)
Basic Tuple operations
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.
T1= (1, 2, 3, 4, 5,
6, 7, 8, 9)
It concatenates the tuple T1=T1+(10,)
Concatenation mentioned on either side of the
operator.
Print(T1)
print(i)
Output
1
The for loop is used to iterate
Iteration 2
over the tuple elements.
T1=(1,2,3,4,5)
It is used to get the length of
Length
the tuple.
len(T1) = 5
List VS Tuple
SN List Tuple
The literal syntax of list is The literal syntax of the tuple is
1
shown by the []. shown by the ().
2 The List is mutable. The tuple is immutable.
The List has the variable
3 The tuple has the fixed length.
length.
The list provides more The tuple provides less
4
functionality than tuple. functionality than the list.
The list Is used in the The tuple is used in the cases
scenario in which we need where we need to store the
to store the simple read-only collections i.e., the
5
collections with no value of the items can not be
constraints where the value changed. It can be used as the
of the items can be changed. key inside the dictionary.
6 Syntax
7. Example
Python Sets
A set is an unordered collection of items. Every element is unique (no duplicates) and must be
immutable (which cannot be changed).
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().
Output:
looping through the set elements …
Friday
Tuesday
Monday
Saturday
Thursday
Sunday
Wednesday
Output:
looping through the set elements …
Friday
Tuesday
Monday
Saturday
Thursday
Sunday
Wednesday
1. Days1 = {“Monday”,”Tuesday”,”Wednesday”,”Thursday”}
2. Days2 = {“Friday”,”Saturday”,”Sunday”}
3. print(Days1|Days2) #printing the union of the sets
Output:
{‘Friday’, ‘Sunday’, ‘Saturday’, ‘Tuesday’, ‘Wednesday’, ‘Monday’, ‘Thursday’}
Python also provides the union() method which can also be used to calculate the union of two
sets. Consider the following example.
Example 2: using union() method
1. Days1 = {“Monday”,”Tuesday”,”Wednesday”,”Thursday”}
2. Days2 = {“Friday”,”Saturday”,”Sunday”}
3. print(Days1.union(Days2)) #printing the union of the sets
Output:
{‘Friday’, ‘Monday’, ‘Tuesday’, ‘Thursday’, ‘Wednesday’, ‘Sunday’, ‘Saturday’}
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.
SN Method Description
It adds an item to the set. It has no
effect if the item is already present in
the set.
GEEK = {‘g’, ‘e’, ‘k’}
1 add(item)
# adding ‘s’
GEEK.add(‘s’)
set1.clear()
2 clear()
print(“\nSet after using clear()
function”)
print(set1)
print(set2)
result =
4 difference_update(….) A.symmetric_difference_update(B)
print(‘A = ‘, A)
print(‘B = ‘, B)
print(‘result = ‘, result)
print(fruits)
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.
In python, strings can be created by enclosing the character or the sequence of characters in the
quotes. Python allows us to use single quotes, double quotes, or triple quotes to create the
string.
Consider the following example in python to create a string.
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.
Method Description
It capitalizes the first character of the String. This
capitalize()
function is deprecated in python3
string = “python is AWesome.”
b = string.capitalize()
print(‘New String: ‘, b)
print(‘Capitalized String:’, b)
casefold()
center(width
,fillchar) new_string = string.center(24)
print(song.replace(‘cold’, ‘hurt’))
Index()
result = sentence.index(‘n’)
endswith()
# returns False
print(result)
String Operators
Operator Description
It is known as concatenation operator used to join the
strings given either side of the operator.
1. str = “Hello”
+ 2. str1 = ” world”
3. print(str+str1)
# prints Hello world
Dictionary
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.
# dictionary with integer keys
my_dict = {1: ‘apple’, 2: ‘ball’}
Python has a set of built-in methods that you can use on dictionaries.
Method Description
Removes all the elements from the dictionary
car = {
“brand”: “Ford”,
“model”: “Mustang”,
“year”: 1964
clear() }
car.clear()
print(car)
print(x)
fromkeys() y = 0
thisdict = dict.fromkeys(x, y)
print(thisdict)
print(x)
“brand”: “Ford”,
“model”: “Mustang”,
x = car.items()
print(x)
print(x)
print(car)
print(car)
“brand”: “Ford”,
“model”: “Mustang”,
“year”: 1964
setdefault() }
x = car.setdefault(“model”, “Bronco”)
print(x)
“brand”: “Ford”,
“model”: “Mustang”,
update()
“year”: 1964
car.update({“color”: “White”})
car.update({“age”:34})
print(car)
“brand”: “Ford”,
“model”: “Mustang”,
“year”: 1964
values() }
x = car.values()
print(x)
Unit-3
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.
Types of functions in python
1.Inbuilt functions
Python provide us various inbuilt functions like range() or print(),input().
By using functions, we can avoid rewriting same logic/code again and again in a program.
We can call python functions any number of times in a program and from any place in a
program.
We can track a large python program easily when it is divided into multiple functions.
Reusability is the main achievement of python functions.
Improving clarity of the code
Information hiding
Reducing duplication of code
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. defhello_world():
2. print(“hello world”)
3.
4. hello_world()
Output:
hello world
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. defmy_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.
Consider the following example which contains a function that accepts a string as the parameter
and prints it.
Example
Output:
Enter a: 10
Enter b: 20
Sum = 30
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
res2 = f(a, b)
# call by value
string = “hello”
def test(string):
string = “world”
test(string)
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:
(‘inside the list’, [1, 2, 3, 4, 5, 20])
In python, the variables are defined with the two types of scopes.
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
The factorial of 4 is 24
Advantages of Recursion
1. Recursive functions make the code look clean and elegant.
2. A complex task can be broken down into simpler sub-problems using recursion.
3. Sequence generation is easier with recursion than using some nested iteration.
Disadvantages of Recursion
1. Sometimes the logic behind recursion is hard to follow through.
2. Recursive calls are expensive (inefficient) as they take up a lot of memory and time.
3. Recursive functions are hard to debug.
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
In this example, we will create a module named as file.py which contains a function func that
contains a code to print some message on the console.
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.
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.
Example:
import file;
name = input(“Enter the name?”)
file.displayMsg(name)
Output:
Enter the name?John
Hi John
calculation.py:
1. #place the code in the calculation.py
2. defsummation(a,b):
3. return a+b
4. defmultiplication(a,b):
5. return a*b;
6. defdivide(a,b):
7. return a/b;
Main.py:
1. fromcalculation import summation
2. #it will import only the summation() from calculation.py
3. a = int(input(“Enter the first number”))
4. b = int(input(“Enter the second number”))
5. print(“Sum = “,summation(a,b))
6. Output:
Enter the first number10
Sum = 30
The from…import statement is always better to use if we know the attributes to be imported
from the module in advance. It doesn’t let our code to be heavier. We can also import all the
attributes from a module by using *.
Consider the following syntax.
1. from<module> import *
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.
#the module calculation of previous example is imported in this example as cal. import calculatio
n as cal;
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
Example
1. importjson
2.
3. List = dir(json)
4.
5. print(List)
Output:
[‘JSONDecoder’, ‘JSONEncoder’, ‘__all__’, ‘__author__’, ‘__builtins__’, ‘__cached__’,
‘__doc__’,
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)
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
This module, as mentioned in the Python 3’s documentation, implements pseudo-random number
generators for various distributions.
1. First, we create a directory and give it a package name, preferably related to its operation.
2. Then we put the classes and the required functions in it.
3. Finally we create an __init__.py file inside the directory, to let Python know that the directory is
a package.
Example of Creating 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.
def __init__(self):
def outModels(self):
print(‘\t%s ‘ % model)
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.
from cars import b
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:
ModBMW = Bmw()
ModBMW.outModels()
ModAudi = Audi()
ModAudi.outModels()
Unit-4
Exception Handling
An exception is an error that happens during execution of a
program. When that
program to crash.
in a program. When you think that you have a code which can
produce an error then
you can use exception handling.
Types of Exception
1)Build in
2) User Define
1)Build in Exception
Below is some common exceptions errors in Python:
IOError
If the file cannot be opened.
ImportError
If python cannot find the module
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
Raised when one of the built-in functions (input() or raw_input())
hits an
Syntax
try:
except:
exception handling
try:
print (1/0)
except ZeroDivisionError:
Output
Build in
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 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”
3.Write ()
This method writes a sequence of strings to the file.
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
resources taken up by the open file.
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.
File Handling Examples
print fh.read()
print fh.readline()
print fh.readlines()
write(“Hello World”)
fh.close()
To write to a file, use:
fh = open(“hello.txt”, “w”)
fh.writelines(lines_of_text)
fh.close()
fh.close()
print fh.read()
fh.close()
Python os module provides methods that help you perform file-processing operations, such as
renaming and deleting files.
To use this module you need to import it first and then you can call any related functions.
Syntax
os.rename(current_file_name, new_file_name)
Example
Following is the example to rename an existing file test1.txt −
#!/usr/bin/python
import os
Syntax
os.remove(file_name)
Example
Following is the example to delete an existing file test2.txt −
#!/usr/bin/python
import os
os.remove(“text2.txt”)
One of the popular approaches to solve a programming problem is by creating objects. This is
known as Object-Oriented Programming (OOP).
1.Class
A class is a blueprint for the object.
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
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.
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
To create a class, use the keyword class:
Example
class MyClass:
x=5
Create Object/Accessing members
Now we can use the class named MyClass to create objects:
Example
p1.age = 40
Example
Insert a function that prints a greeting, and execute it on the p1 object:
class Person:
p1 = Person(“John”, 36)
p1.myfunc()
Output:
my age is 36
Attribute Description
__dict__ This is a dictionary holding the class namespace.
This gives us the class documentation if
__doc__
documentation is present. None otherwise.
__name__ This gives us the class name.
This gives us the name of the module in which the
class is defined.
__module__ In an interactive mode it will give us __main__.
empCount = 0
self.name = name
self.salary = salary
Employee.empCount += 1
def displayCount(self):
def displayEmployee(self):
Output
Employee.__name__: Employee
Employee.__module__: __main__
Employee.__bases__: ()
Employee.__dict__: {‘__module__’: ‘__main__’, ‘displayCount’:
Destroying objects.
A class implements the special method __del__(), called a destructor, that is invoked when the
instance is about to be destroyed. This method might be used to clean up any non memory
resources used by an instance.
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
CLASS:BCA3rdSem
Batch: 2019-2021
Python
Notes as per IKGPTU Syllabus
Name of Faculty: Ms<Jatinderpal Kaur>
Faculty of IT Department, SBS College. Ludhiana
Unit-I
6-34
Operators and Expressions: Operators in Python,
Expressions, Precedence, Associativity of Operators,
Non Associative Operators.
Unit-II
Unit-IV
Exception Handling: Exceptions, Built-in exceptions,
Exception handling, User defined exceptions in
Python.
Unit- 1
What is Python?
Python is a popular programming language. It was created by Guido van Rossum, and released in
1991.
It is used for:
Python Features
Python provides lots of features that are listed below.
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.
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.
10) Integrated
It can be easily integrated with languages like C, C++, JAVA etc.
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 .
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:
In the System variable window, find the Path variable and click Edit:
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:
C:>python –version
Python 3.4.3
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”.
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.
Step 7) You can see the output of your program at the bottom of the screen.
If the help function is passed without an argument, then the interactive help utility starts up on the
console.
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
Most of the programming languages like C, C++, Java use braces { } to define a block of code.
Python uses indentation.
A code block (body of a function, loop etc.) starts with indentation and ends with the first
unindented line. The amount of indentation is up to you, but it must be consistent throughout that
block.
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.
It extends up to the newline character. Comments are for programmers for better understanding of
a program. Python Interpreter ignores comment.
For Example
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.
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
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.
1. number = 10
print (a)
print (b)
print (c)
Constants
A constant is a type of variable whose value cannot be changed. It is helpful to think of constants
as containers that hold information which cannot be changed later.types
(int,float,double,char,strings)
1. PI = 3.14
2. GRAVITY = 9.8
Create a main.py
1. import constant
2. print(constant.PI)
3. print(constant.GRAVITY)
When you run the program, the output will be:
3.14
9.8
Data Type in Python
1. Number Data Type in Python
Python supports integers, floating point numbers and complex numbers. They are defined as int,
float and complex class 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. 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
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.).
# Tuple having integers
print(my_tuple)
# Output:
(1, 2, 3,4)
4.Python Strings
A string is a sequence of characters. A character is simply a symbol. Strings can be created by
enclosing characters inside a single quote or double quotes. Even triple quotes can be used in
Python but generally used to represent multiline strings and docstrings.
# all of the following are equivalent
my_string = ‘Hello’
print(my_string)
print(my_string)
5.Python Sets
A set is an unordered collection of items. Every element is unique (no duplicates) and must be
immutable (which cannot be changed).
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
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.
Creating a dictionary is as simple as placing items inside curly braces {} separated by comma.
An item has a key and the corresponding value expressed as a pair, key: value.
my_dict = {1: ‘apple’, 2: ‘ball’}
# initializing string
s = “10010”
s = “10010”
c = int(s)
print (c)
e = float(s)
print (e)
Output:
We can also output data to a file, but this will be discussed later. An example use is given below.
a=5
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])
c=a+b
print(c)
Python Import
A module is a file containing Python definitions and statements. Python modules have a filename
and end with the extension .py.
Definitions inside a module can be imported to another module or the interactive interpreter in
Python. We use the import keyword to do this.
For example, we can import the math module by typing in import math.
import math
r=int(input(“enter the radius”))
area=(math.pi)*r*r;
print(area)output:
3.141592653589793
Operators in Python
Operators are used to perform operations on variables and values.
Python divides the operators in the following groups:
Arithmetic operators
Assignment operators
Comparison operators
Logical operators
Identity operators
Membership operators
Bitwise operators
!= Not equal x != y
> Greater than x>y
< Less than x<y
>= Greater than or equal to x >= y
<= Less than or equal to x <= y
Returns True if a
in x in y
sequence with the
specified value is
present in the object
Returns True if a
sequence with the
not in x not in y
specified value is not
present in the 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.
1. List comprehension
The syntax for list comprehension is shown below:
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
The syntax for generator expression is shown below:
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
You can use the following construct for one-liner conditions:
Example:
>>> x = “1” if True else “2”
>>> x
‘1’
Precedence Order
When two operators share an operand, the operator with the higher precedence goes first. For
example, since multiplication has a higher precedence than addition, a + b * c is treated as a + (b
* c), and a * b + c is treated as (a * b) + c.(BODMAS)
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.
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.
Unit-2
Control Structures
Types
1.Decision Making Statements
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:
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
2 If(Num < 10):
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
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
2 if(num > 10):
Elif statements are similar to if-else statements but elif statements evaluate multiple conditions.
Syntax:
if (condition):
elif (condition):
#Set of statements to be executed when if condition is false and elif condition is true
else:
#Set of statement to be executed when both if and elif conditions are false
Example: 1
a=int(input(“enter the number to find +ve or -ve or whole number”))
if(a>0):
print(“number is +ve”)
elif(a==0):
print(“number is -ve”)
#4) Nested if/ladder statements
Nested if-else statements mean that an if statement or if-else statement is present inside another if
or if-else block. Python provides this feature as well, this in turn will help us to check multiple
conditions in a given program.
An if statement present inside another if statement which is present inside another if statements
and so on.
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
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”)
Syntax:
if (condition):
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”)
elif(a==6):
print(“today is friday”)
elif(a==7):
print(“today is saturday”)
We use while loop when we don’t know the number of times to iterate.
3 parts of loop
1.intialization (Starting point)
2.condition (ending point)
3.increment /decrement
Syntax:
while (expression): block of statements Increment or decrement operator
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
Syntax:
for var in sequence: Block of code
Here var will take the value from the sequence and execute it until all the values in the sequence
are done.
Example
for i in range(1,11):
Print(i)
output
1 2 3 4 5 6 7 8 9 10
Python break statement
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;
example
for i in range(1,11):
if i==5:
break;
print(i);
output
1234
#loop statements
continue;
#the code to be skipped
Example
i=1; #initializing a local variable
for i in range(1,11):
if i==5:
continue;
print(i);
Output:
1
10
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
4. my_list = [1, 2, 3]
# nested list
# Output: p
print(my_list[0])
# Output: o
print(my_list[2])
# Output: e
print(my_list[4])
SN Function Description
The element represented by the object obj
is added to the list.
a=[1,2,3]
1 list.append(obj) a.append(4)
print(a)
It removes all the elements from the list.
a=[1,2,3]
2 list.clear() a.clear()
print(a)
3 List.copy() b=a.copy()
print(b)
List2=[4,5,6]
5 list.extend(seq)
List1.extend(List2)
Print(List1)
print(S)
9 list.remove(obj) L.remove(1)
Print(L)
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: ()
my_tuple = (1, 2, 3)
# nested tuple
print(my_tuple)
A tuple can also be created without using parentheses. This is known as tuple packing.for
example
print(tuple2)
Basic Tuple operations
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.
T1= (1, 2, 3, 4, 5,
6, 7, 8, 9)
It concatenates the tuple T1=T1+(10,)
Concatenation mentioned on either side of the
operator.
Print(T1)
print(i)
Output
1
The for loop is used to iterate
Iteration 2
over the tuple elements.
T1=(1,2,3,4,5)
It is used to get the length of
Length
the tuple.
len(T1) = 5
List VS Tuple
SN List Tuple
The literal syntax of list is The literal syntax of the tuple is
1
shown by the []. shown by the ().
2 The List is mutable. The tuple is immutable.
The List has the variable
3 The tuple has the fixed length.
length.
The list provides more The tuple provides less
4
functionality than tuple. functionality than the list.
The list Is used in the The tuple is used in the cases
scenario in which we need where we need to store the
to store the simple read-only collections i.e., the
5
collections with no value of the items can not be
constraints where the value changed. It can be used as the
of the items can be changed. key inside the dictionary.
6 Syntax
7. Example
Python Sets
A set is an unordered collection of items. Every element is unique (no duplicates) and must be
immutable (which cannot be changed).
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().
Output:
looping through the set elements …
Friday
Tuesday
Monday
Saturday
Thursday
Sunday
Wednesday
Output:
looping through the set elements …
Friday
Tuesday
Monday
Saturday
Thursday
Sunday
Wednesday
1. Days1 = {“Monday”,”Tuesday”,”Wednesday”,”Thursday”}
2. Days2 = {“Friday”,”Saturday”,”Sunday”}
3. print(Days1|Days2) #printing the union of the sets
Output:
{‘Friday’, ‘Sunday’, ‘Saturday’, ‘Tuesday’, ‘Wednesday’, ‘Monday’, ‘Thursday’}
Python also provides the union() method which can also be used to calculate the union of two
sets. Consider the following example.
Example 2: using union() method
1. Days1 = {“Monday”,”Tuesday”,”Wednesday”,”Thursday”}
2. Days2 = {“Friday”,”Saturday”,”Sunday”}
3. print(Days1.union(Days2)) #printing the union of the sets
Output:
{‘Friday’, ‘Monday’, ‘Tuesday’, ‘Thursday’, ‘Wednesday’, ‘Sunday’, ‘Saturday’}
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.
SN Method Description
It adds an item to the set. It has no
effect if the item is already present in
the set.
GEEK = {‘g’, ‘e’, ‘k’}
1 add(item)
# adding ‘s’
GEEK.add(‘s’)
set1.clear()
2 clear()
print(“\nSet after using clear()
function”)
print(set1)
print(set2)
result =
4 difference_update(….) A.symmetric_difference_update(B)
print(‘A = ‘, A)
print(‘B = ‘, B)
print(‘result = ‘, result)
print(fruits)
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.
In python, strings can be created by enclosing the character or the sequence of characters in the
quotes. Python allows us to use single quotes, double quotes, or triple quotes to create the
string.
Consider the following example in python to create a string.
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.
Method Description
It capitalizes the first character of the String. This
capitalize()
function is deprecated in python3
string = “python is AWesome.”
b = string.capitalize()
print(‘New String: ‘, b)
print(‘Capitalized String:’, b)
casefold()
center(width
,fillchar) new_string = string.center(24)
print(song.replace(‘cold’, ‘hurt’))
Index()
result = sentence.index(‘n’)
endswith()
# returns False
print(result)
String Operators
Operator Description
It is known as concatenation operator used to join the
strings given either side of the operator.
1. str = “Hello”
+ 2. str1 = ” world”
3. print(str+str1)
# prints Hello world
Dictionary
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.
# dictionary with integer keys
my_dict = {1: ‘apple’, 2: ‘ball’}
Python has a set of built-in methods that you can use on dictionaries.
Method Description
Removes all the elements from the dictionary
car = {
“brand”: “Ford”,
“model”: “Mustang”,
“year”: 1964
clear() }
car.clear()
print(car)
print(x)
fromkeys() y = 0
thisdict = dict.fromkeys(x, y)
print(thisdict)
print(x)
“brand”: “Ford”,
“model”: “Mustang”,
x = car.items()
print(x)
print(x)
print(car)
print(car)
“brand”: “Ford”,
“model”: “Mustang”,
“year”: 1964
setdefault() }
x = car.setdefault(“model”, “Bronco”)
print(x)
“brand”: “Ford”,
“model”: “Mustang”,
update()
“year”: 1964
car.update({“color”: “White”})
car.update({“age”:34})
print(car)
“brand”: “Ford”,
“model”: “Mustang”,
“year”: 1964
values() }
x = car.values()
print(x)
Unit-3
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.
Types of functions in python
1.Inbuilt functions
Python provide us various inbuilt functions like range() or print(),input().
By using functions, we can avoid rewriting same logic/code again and again in a program.
We can call python functions any number of times in a program and from any place in a
program.
We can track a large python program easily when it is divided into multiple functions.
Reusability is the main achievement of python functions.
Improving clarity of the code
Information hiding
Reducing duplication of code
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. defhello_world():
2. print(“hello world”)
3.
4. hello_world()
Output:
hello world
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. defmy_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.
Consider the following example which contains a function that accepts a string as the parameter
and prints it.
Example
Output:
Enter a: 10
Enter b: 20
Sum = 30
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
res2 = f(a, b)
# call by value
string = “hello”
def test(string):
string = “world”
test(string)
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:
(‘inside the list’, [1, 2, 3, 4, 5, 20])
In python, the variables are defined with the two types of scopes.
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
The factorial of 4 is 24
Advantages of Recursion
1. Recursive functions make the code look clean and elegant.
2. A complex task can be broken down into simpler sub-problems using recursion.
3. Sequence generation is easier with recursion than using some nested iteration.
Disadvantages of Recursion
1. Sometimes the logic behind recursion is hard to follow through.
2. Recursive calls are expensive (inefficient) as they take up a lot of memory and time.
3. Recursive functions are hard to debug.
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
In this example, we will create a module named as file.py which contains a function func that
contains a code to print some message on the console.
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.
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.
Example:
import file;
name = input(“Enter the name?”)
file.displayMsg(name)
Output:
Enter the name?John
Hi John
calculation.py:
1. #place the code in the calculation.py
2. defsummation(a,b):
3. return a+b
4. defmultiplication(a,b):
5. return a*b;
6. defdivide(a,b):
7. return a/b;
Main.py:
1. fromcalculation import summation
2. #it will import only the summation() from calculation.py
3. a = int(input(“Enter the first number”))
4. b = int(input(“Enter the second number”))
5. print(“Sum = “,summation(a,b))
6. Output:
Enter the first number10
Sum = 30
The from…import statement is always better to use if we know the attributes to be imported
from the module in advance. It doesn’t let our code to be heavier. We can also import all the
attributes from a module by using *.
Consider the following syntax.
1. from<module> import *
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.
#the module calculation of previous example is imported in this example as cal. import calculatio
n as cal;
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
Example
1. importjson
2.
3. List = dir(json)
4.
5. print(List)
Output:
[‘JSONDecoder’, ‘JSONEncoder’, ‘__all__’, ‘__author__’, ‘__builtins__’, ‘__cached__’,
‘__doc__’,
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)
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
This module, as mentioned in the Python 3’s documentation, implements pseudo-random number
generators for various distributions.
1. First, we create a directory and give it a package name, preferably related to its operation.
2. Then we put the classes and the required functions in it.
3. Finally we create an __init__.py file inside the directory, to let Python know that the directory is
a package.
Example of Creating 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.
def __init__(self):
def outModels(self):
print(‘\t%s ‘ % model)
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.
from cars import b
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:
ModBMW = Bmw()
ModBMW.outModels()
ModAudi = Audi()
ModAudi.outModels()
Unit-4
Exception Handling
An exception is an error that happens during execution of a
program. When that
program to crash.
in a program. When you think that you have a code which can
produce an error then
you can use exception handling.
Types of Exception
1)Build in
2) User Define
1)Build in Exception
Below is some common exceptions errors in Python:
IOError
If the file cannot be opened.
ImportError
If python cannot find the module
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
Raised when one of the built-in functions (input() or raw_input())
hits an
Syntax
try:
except:
exception handling
try:
print (1/0)
except ZeroDivisionError:
Output
Build in
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 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”
3.Write ()
This method writes a sequence of strings to the file.
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
resources taken up by the open file.
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.
File Handling Examples
print fh.read()
print fh.readline()
print fh.readlines()
write(“Hello World”)
fh.close()
To write to a file, use:
fh = open(“hello.txt”, “w”)
fh.writelines(lines_of_text)
fh.close()
fh.close()
print fh.read()
fh.close()
Python os module provides methods that help you perform file-processing operations, such as
renaming and deleting files.
To use this module you need to import it first and then you can call any related functions.
Syntax
os.rename(current_file_name, new_file_name)
Example
Following is the example to rename an existing file test1.txt −
#!/usr/bin/python
import os
Syntax
os.remove(file_name)
Example
Following is the example to delete an existing file test2.txt −
#!/usr/bin/python
import os
os.remove(“text2.txt”)
One of the popular approaches to solve a programming problem is by creating objects. This is
known as Object-Oriented Programming (OOP).
1.Class
A class is a blueprint for the object.
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
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.
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
To create a class, use the keyword class:
Example
class MyClass:
x=5
Create Object/Accessing members
Now we can use the class named MyClass to create objects:
Example
p1.age = 40
Example
Insert a function that prints a greeting, and execute it on the p1 object:
class Person:
p1 = Person(“John”, 36)
p1.myfunc()
Output:
my age is 36
Attribute Description
__dict__ This is a dictionary holding the class namespace.
This gives us the class documentation if
__doc__
documentation is present. None otherwise.
__name__ This gives us the class name.
This gives us the name of the module in which the
class is defined.
__module__ In an interactive mode it will give us __main__.
empCount = 0
self.name = name
self.salary = salary
Employee.empCount += 1
def displayCount(self):
def displayEmployee(self):
Output
Employee.__name__: Employee
Employee.__module__: __main__
Employee.__bases__: ()
Employee.__dict__: {‘__module__’: ‘__main__’, ‘displayCount’:
Destroying objects.
A class implements the special method __del__(), called a destructor, that is invoked when the
instance is about to be destroyed. This method might be
Click here to download the pdf notes
https://www.javatpoint.com/python-modules
https://www.tutorialspoint.com/execute_python_online.php
https://www.onlinegdb.com/online_python_compiler
COURSE FEATURES
Lectures0
Quizzes0
Skill levelAll levels
Students4
AssessmentsSelf
LEAVE A REPLY
You must be logged in to post a comment.
YOU MAY LIKE
Pooja Manchanda
SYSTEMATIC BACTERIOLOGY
0
Free
Pooja Manchanda
HUMAN ANATOMY AND PHYSIOLOGY-1
0
Free
IT
C# Programming
0
Free
Simranjeet Singh
INDUSTRIAL RELATIONS AND LABOUR LAWS
1
Free
Pooja Manchanda
BIOCHEMICAL METABOLISM
0
Free
Pooja Manchanda
SYSTEMATIC BACTERIOLOGY
0
Free
Pooja Manchanda
HUMAN ANATOMY AND PHYSIOLOGY-1
0
Free
IT
C# Programming
0
Free
Simranjeet Singh
INDUSTRIAL RELATIONS AND LABOUR LAWS
1
Free
Pooja Manchanda
BIOCHEMICAL METABOLISM
0
Free
Pooja Manchanda
SYSTEMATIC BACTERIOLOGY
0
Free
SBS is managed by a non-profit organisation (Zayn Educational Trust) registered as a Trust and
charitable society. Its aim is to develop as a business school of excellence over time in Punjab.
USEFUL LINKS
My Account
Online Courses
Scholarship
Blog
Events
International Students
Recent Posts
Job opening at Om Careers
Recruitment drive by VibrantMinds Technologies- A Campus Recruitment, Online Assessment & IT
Training Company!
Job opening at Keva Kaipo Industries Pvt Ltd.
Accountant, Marketing Executive and Computer Operator required at Champion Enterprises
CONNECT US
+918556001933
+919815188836
info@sbs.ac.in
Ramgarh, Chandigarh Road, Ludhiana
Sign up
Need Help? Chat with us
Enquiry Form