python unit 2
python unit 2
ANKUR 1
L.J. GANDHI BCA COLLEGE, MODASA UNIT:2 BCA-601-PYTHON
If statement in python
if statement is the most simple decision-making statement.
It is used to decide whether a certain statement or block of statements will be executed or not.
For example, if a certain condition is true then a block of statement is executed otherwise not.
Syntax:
if test expression :
statement(s)
Here, the program evaluates the test expression and will execute statement(s) only if
the test expression is True.
If the test expression is False, the statement(s) is not executed.
In Python, the body of the if statement is indicated by the indentation.
The body starts with an indentation and the first unindented line marks the end.
Python interprets non-zero values as True.
None and 0 are interpreted as False.
As we know, python uses indentation to identify a block. So the block under an if statement
will be identified as shown in the below example:
if condition:
statement1
statement2
ANKUR 2
L.J. GANDHI BCA COLLEGE, MODASA UNIT:2 BCA-601-PYTHON
Output :
enter the number = 10
Number is even
Output :
Enter a = 100
Enter b = 120
Enter c = 130
c is largest
ANKUR 3
L.J. GANDHI BCA COLLEGE, MODASA UNIT:2 BCA-601-PYTHON
Output :
i is less than 15
ANKUR 4
L.J. GANDHI BCA COLLEGE, MODASA UNIT:2 BCA-601-PYTHON
The if..else statement evaluates test expression and will execute the body of if only when the
test condition is True.
If the condition is False, the body of else is executed.
Indentation is used to separate the blocks.
ANKUR 5
L.J. GANDHI BCA COLLEGE, MODASA UNIT:2 BCA-601-PYTHON
Output :
Positive or greater than Zero
Output :
Enter your age = 90
You are eligible to vote !!
Output :
enter the number = 10
Number is even
ANKUR 6
L.J. GANDHI BCA COLLEGE, MODASA UNIT:2 BCA-601-PYTHON
Output :
True
ANKUR 7
L.J. GANDHI BCA COLLEGE, MODASA UNIT:2 BCA-601-PYTHON
The elif is short for else if. It allows us to check for multiple expressions.
If the condition for if is False, it checks the condition of the next elif block and so on.
If all the conditions are False, the body of else is executed.
Only one block among the several if...elif...else blocks is executed according to the condition.
The if block can have only one else block. But it can have multiple elif blocks.
ANKUR 8
L.J. GANDHI BCA COLLEGE, MODASA UNIT:2 BCA-601-PYTHON
if num > 0:
print("Positive number")
elif num == 0:
print("Zero")
else:
print("Negative number")
Output :
Positive number
if number == 10:
print("number is equals to 10")
else:
print("number is not equal to 10, 50 or 100");
Output :
Enter the number = 15
number is not equal to 10, 50 or 100
ANKUR 9
L.J. GANDHI BCA COLLEGE, MODASA UNIT:2 BCA-601-PYTHON
else:
print("Sorry you are fail")
Output:
Enter the marks== 87
Congrats ! you scored grade A ...
ANKUR 10
L.J. GANDHI BCA COLLEGE, MODASA UNIT:2 BCA-601-PYTHON
if num >= 0:
if num == 0:
print("Zero")
else:
print("Positive number")
else:
print("Negative number")
Output :
Enter a number = 7
Positive number
ANKUR 11
L.J. GANDHI BCA COLLEGE, MODASA UNIT:2 BCA-601-PYTHON
1. Break Statement
The break statement in Python is used to terminate a loop, means whenever the interpreter
encounters the break keyword, it simply exits out of the loop.
Once it breaks out of the loop, the control shifts to the immediate next statement.
Also, if the break statement is used inside a nested loop, it terminates the innermost loop and
the control shifts to the next statement in the outer loop.
Break Example :
for letter in 'geeksforgeeks':
Output :
Current Letter : e
2. Continue Statement
Whenever the interpreter encounters a continue statement in Python, it will skip the
execution of the rest of the statements in that loop and proceed with the next iteration.
This means it returns the control to the beginning of the loop.
Unlike the break statement, continue statement does not terminate or exit out of the loop,
Rather, it continues with the next iteration.
ANKUR 12
L.J. GANDHI BCA COLLEGE, MODASA UNIT:2 BCA-601-PYTHON
Continue Example :
for letter in 'geeksforgeeks':
Output :
Current Letter : g
Current Letter : k
Current Letter : f
Current Letter : o
Current Letter : r
Current Letter : g
Current Letter : k
3. Pass Statement
Assume we have a loop that is not implemented yet, but needs to implemented in the future.
In this case, if you leave the loop empty, the interpreter will throw an error.
To avoid this, you can use the pass statement to construct a block that does nothing means
contains no statements.
We use pass statement to write empty loops.
Pass Example :
# An empty loop
for letter in 'geeksforgeeks':
pass
print ('Last Letter :', letter)
Output :
Last Letter : s
ANKUR 13
L.J. GANDHI BCA COLLEGE, MODASA UNIT:2 BCA-601-PYTHON
Looping in python
The flow of the programs written in any programming language is sequential by default.
Sometimes we may need to alter the flow of the program.
The execution of a specific code may need to be repeated several numbers of times.
For this purpose, The programming languages provide various types of loops which are
capable of repeating some specific code several numbers of times.
Advantages of loops
It provides code re-usability.
Using loops, we do not need to write the same code again and again.
Using loops, we can traverse over the elements of data structures (array or linked lists).
Loop Description
The for loop is used in the case where we need to execute some part of the
For loop code until the given condition is satisfied.
The for loop is also called as a per-tested loop.
It is better to use for loop if the number of iteration is known in advance.
The while loop is to be used in the scenario where we don't know the number
of iterations in advance.
While loop The block of statements is executed in the while loop until the condition
specified in the while loop is satisfied.
It is also called a pre-tested loop
ANKUR 14
L.J. GANDHI BCA COLLEGE, MODASA UNIT:2 BCA-601-PYTHON
Output:
P
y
t
h
o
n
ANKUR 15
L.J. GANDHI BCA COLLEGE, MODASA UNIT:2 BCA-601-PYTHON
Output :
5
10
15
20
25
30
35
40
45
50
Output :
The sum is = 183
ANKUR 16
L.J. GANDHI BCA COLLEGE, MODASA UNIT:2 BCA-601-PYTHON
Output :
0123456789
Output :
Enter the number 10
10 * 1 = 10
10 * 2 = 20
10 * 3 = 30
10 * 4 = 40
10 * 5 = 50
ANKUR 17
L.J. GANDHI BCA COLLEGE, MODASA UNIT:2 BCA-601-PYTHON
Output :
Enter the rows = 5
*
**
***
****
*****
Output :
Enter the rows = 5
1
22
333
4444
55555
ANKUR 18
L.J. GANDHI BCA COLLEGE, MODASA UNIT:2 BCA-601-PYTHON
Output :
0
1
2
3
4
for loop completely exhausted, since there is no break.
Example : 2
for i in range(0,5):
print(i)
break;
else:
print("for loop is exhausted");
print("The loop is broken due to break statement...came out of the loop")
Output :
0
The loop is broken due to the break statement...came out of the loop.
ANKUR 19
L.J. GANDHI BCA COLLEGE, MODASA UNIT:2 BCA-601-PYTHON
Output :
0123456789
ANKUR 20
L.J. GANDHI BCA COLLEGE, MODASA UNIT:2 BCA-601-PYTHON
Output :
Enter the number : 10
10 X 1 = 10
10 X 2 = 20
10 X 3 = 30
10 X 4 = 40
10 X 5 = 50
10 X 6 = 60
10 X 7 = 70
10 X 8 = 80
10 X 9 = 90
10 X 10 = 100
Output :
Hi! we are inside the infinite while loop
Hi! we are inside the infinite while loop
ANKUR 21
L.J. GANDHI BCA COLLEGE, MODASA UNIT:2 BCA-601-PYTHON
Example : 1
i=1
while(i<=5):
print(i)
i=i+1
else:
print("The while loop exhausted")
Output :
1
2
3
4
5
Example : 2
i=1
while(i<=5):
print(i)
i=i+1
if(i==3):
break
else:
print("The while loop exhausted")
Output :
1
2
ANKUR 22
L.J. GANDHI BCA COLLEGE, MODASA UNIT:2 BCA-601-PYTHON
Example to illustrate the use of else statement with the while loop
counter = 0
Output :
Inside loop
Inside loop
Inside loop
Inside else
Here, we use a counter variable to print the string inside loop three times.
On the fourth iteration, the condition in while becomes False.
Hence, the else part is executed.
ANKUR 23
L.J. GANDHI BCA COLLEGE, MODASA UNIT:2 BCA-601-PYTHON
arrays in Python
An array is defined as a collection of items that are stored at contiguous memory locations.
It is a container which hold a fixed number of items & the items should be of the same type.
An array is popular in most programming languages like C/C++, JavaScript, etc.
A combination of the arrays could save a lot of time by reducing the overall size of the code.
Example
import array as myarray
abc = myarray.array('d', [2.5, 4.9, 6.7])
ANKUR 24
L.J. GANDHI BCA COLLEGE, MODASA UNIT:2 BCA-601-PYTHON
Example
import array as arr
a = arr.array('d', [1.1, 3.5, 4.5])
print(a)
Output :
array('d', [1.1, 3.5, 4.5])
Example
import array as arr
a = arr.array('i', [2, 4, 6, 8])
print("First element:", a[0])
print("Second element:", a[1])
print("Second last element:", a[-1])
Output :
First element: 2
Second element: 4
Second last element: 8
Example
import array
balance = array.array('i', [300,200,100])
print(balance[1]) # Output : 200
ANKUR 25
L.J. GANDHI BCA COLLEGE, MODASA UNIT:2 BCA-601-PYTHON
Example
import array as arr
Output :
array('i', [62, 5, 42])
array('i', [2, 5, 62])
array('i', [52, 48, 5])
array('i', [2, 5, 62, 5, 42, 52, 48, 5])
Example
import array
balance = array.array('i', [300,200,100])
balance.insert(2, 150)
print(balance)
Output :
array('i', [300,200,150,100])
ANKUR 26
L.J. GANDHI BCA COLLEGE, MODASA UNIT:2 BCA-601-PYTHON
Example
import array as myarr
a=myarr.array('b',[3,6,4,8,10,12,14,16,18,20])
a[0]=99
print(a)
Output :
array('b', [99, 6, 4, 8, 10, 12, 14, 16, 18, 20])
Example
import array as myarray
first = myarray.array('b', [2, 3, 4])
first.remove(3)
print(first) # Output : array('b', [2, 4])
Example
import array as myarray
number = myarray.array('b', [2, 3, 4, 5, 6])
print(number.index(3)) # Output : 1
ANKUR 27
L.J. GANDHI BCA COLLEGE, MODASA UNIT:2 BCA-601-PYTHON
Concatenation of array
We can also perform concatenation operations on arrays.
Example
import array as myarr
first = myarr.array('b', [4, 6, 8])
second = myarr.array('b', [9, 12, 15])
numbers = myarr.array('b')
numbers = first + second
print(numbers)
Output :
array('b', [4, 6, 8, 9, 12, 15])
Reverse an Array
This operation will reverse the entire array. Syntax: array.reverse()
Example
import array as myarray
number = myarray.array('b', [1,2, 3])
number.reverse()
print(number)
Output :
array('b', [3, 2, 1])
Example
import array as myarr
number = myarr.array('b', [2, 3, 5, 4,3,3,3])
print(number.count(3))
ANKUR 28
L.J. GANDHI BCA COLLEGE, MODASA UNIT:2 BCA-601-PYTHON
Output :
4
Traverse an Array
You can traverse a python array by using loops, like below:
Example
import array
balance = array.array('i', [300,200,100])
for x in balance:
print(x)
Output :
300
200
100
Array Advantages
Consumes less memory.
Fast as compared to the python List.
Convenient to use.
Helps in reusability of code
Predictable timing with array as the system is well aware of the array’s precise address, and
wherein memory is allocated and stored
ANKUR 29
L.J. GANDHI BCA COLLEGE, MODASA UNIT:2 BCA-601-PYTHON
The first way is to import the entire array module using import statement as, import array
Example
import array
a =array.array('i',[4,6,2,9])
The second way of importing the array module is to give it an alias name as, import array
as ar
Example
import array as ar
a =ar.array('i', [4,6,2,9])
The third way of importing the array module is to write : from array import * where '*'
symbol that represents 'all'.
Example
from array import *
a =array('i',[4,6,2,9])
ANKUR 30
L.J. GANDHI BCA COLLEGE, MODASA UNIT:2 BCA-601-PYTHON
Functions in python
Defining a function
We can define a function using the keyword def followed by function name, we should write
parentheses () which may contain parameters.
Consider the syntax of function, as shown below.
def functionname( para1, para2, ……):
function statements
Example
def sum(a, b):
c = a + b
print(c)
Calling a function
A function can’t run on it’s own, It runs only when we call to it and we can call the function
by it’s name.
While calling the function, we should pass the necessary values to the function in the
parentheses such as: sum(10,15)
In above line, we call the ‘sum’ function and passing two values 10 and 15 to that function.
When this statement is executed, the python interpreter jumps to the function definition and
copies the values 10 and 15 into the parameter ‘a’ and ‘b’ respectively
These values are processed in the function body and result is obtained.
Example : A function that accepts two values and finds their sum.
#a function to add two numbers
def sum(a, b):
c=a+b
print('sum = ', c)
Output :
Sum 25
Sum 12.25
ANKUR 31
L.J. GANDHI BCA COLLEGE, MODASA UNIT:2 BCA-601-PYTHON
Example : Python program to find the sum of two numbers and return the result
from the function.
#a function to add two numbers
def sum(a, b) :
c=a+b
return c #return result
y = sum(1.5, 10.75)
print('The sun is:’, y)
Output :
The sun is: 25
The sun is: 12.25
ANKUR 32
L.J. GANDHI BCA COLLEGE, MODASA UNIT:2 BCA-601-PYTHON
Output:
12 is even
13 is odd
ANKUR 33
L.J. GANDHI BCA COLLEGE, MODASA UNIT:2 BCA-601-PYTHON
ANKUR 34
L.J. GANDHI BCA COLLEGE, MODASA UNIT:2 BCA-601-PYTHON
Output :
[1, 2, 3, 4, 9] 37762552
[1, 2, 3, 4, 9] 37762552
If the object is immutable, the modified value is not available outside the function and if the
object is mutable, its modified version is available outside the function.
You can easily understand above program by this figure:
ANKUR 35
L.J. GANDHI BCA COLLEGE, MODASA UNIT:2 BCA-601-PYTHON
Example: A Python program to create a new object inside the function does not
modify outside object.
#passing a list to a function
def modify (lst):
lst = [10, 11, 12]
print (lst, id(lst))
Output :
[10, 11, 12] 29505976
[1, 2, 3, 4] 29505016
ANKUR 36
L.J. GANDHI BCA COLLEGE, MODASA UNIT:2 BCA-601-PYTHON
Arguments in python
When a function is defined, it may have some parameters which are useful to receive values
from outside of the function which is called ‘formal argument’.
When we call the function, we should pass data or values to the function which is called
‘actual argument’.
In the following code, ‘a’ and ‘b’ are formal arguments and ‘x’ ans ‘y’ are actual arguments.
Example
def sum(a, b): #a, b are formal arguments
c=a+b
print (c)
1. Positional Arguments
These are the arguments passed to a function in correct positional order.
Here, the number of arguments and their positions in the function definition should match
exactly with the number and position of the argument in the function call.
For Example, take a function definition with 2 arguments as: def attach(s1,s2)
Let’s assume that this function attaches the two string as s1+s2 so, while calling this
function, we are supposed to pass only two strings as: attach(‘New’, ‘York’)
Which displays the output as : NewYork
Suppose, we passed ‘York’ first and then ‘New’, then the result will be : ‘YorkNew’.
Also, if we try to pass more than or less than 2 strings, there will be an error.
For Example, if we call the function by passing 3 strings as: attach(‘New’, ‘York’, ‘city’)
then there will be an error displayed.
ANKUR 37
L.J. GANDHI BCA COLLEGE, MODASA UNIT:2 BCA-601-PYTHON
Output :
Total string: NewYork
2. Keyword Arguments
Keyword arguments are arguments that identify the parameters by their names.
For Example, the definition of a function that displays grocery item and its price can be
written as: def grocery(item, price)
At the time of calling this function, we have to pass two values and when we can mention
which value is for what.
For example, grocery(item=‘sugar’, price=50.75)
Here, we mentioning the keyword ‘item’ and its value and then another keyword ‘price’ and
its value and observe these keywords are nothing but the parameters names which receive
these values.
We can change the order of the arguments as: grocery(price=88.00, item=‘oil’)
In this way, even though we change the order of the arguments, there will not be any problem
as the parameters names will guide where to store that value.
ANKUR 38
L.J. GANDHI BCA COLLEGE, MODASA UNIT:2 BCA-601-PYTHON
Output :
Item= sugar
Price = 50.75
Item = oil
Price = 88.00
3. Default Arguments
We can mention some default value for the function parameters in the definition.
Let’s take the definition of grocery() function as: def grocery(item, price=40.00):
Here the first argument is ‘item’ whose default value is not mentioned, but the second
argument is ‘price’ and its default value is mentioned to be 40.00.
At the time of calling this function, if we do not pass ‘price’ value, then the default value of
40.00 is taken amd if we mention the ‘price’ value, then that mentioned value is taken.
So, a default argument is argument that assumes a default value if a value is not provided in
the function call for that argument.
Output :
Item= sugar
Price = 50.75
Item = sugar
Price = 40.00
ANKUR 39
L.J. GANDHI BCA COLLEGE, MODASA UNIT:2 BCA-601-PYTHON
The variable length argument is written with a ‘*’ symbol before it in the function definition
as: def add(farg, *args): where ‘frag’ is the formal argument and ‘*args’ represents
variable length argument.
We can pass 1 or more values to this ‘*args’ and it will store them all in the tuple.
Example : A Python program of the variable length argument and its use.
# variable length arguments demo
def add (farg, *args): # *args can take 0 or more value
print(‘Formal argument = ‘, farg)
sum = 0
for i in args :
sum = sum + i
print(‘sum of all numbers = ‘, (farg + sum))
Output :
Formal argument = 5
Sum of all numbers = 15
Formal argument = 5
Sum of all numbers = 65
ANKUR 40
L.J. GANDHI BCA COLLEGE, MODASA UNIT:2 BCA-601-PYTHON
all() Checks whether all the elements in an iterable are truthy values or not.
any() Returns True if at least one element in the given iterable is truthy value or
boolean True. Returns False for empty or falsy value (such as 0, False, none).
bool() Converts a value to the bool class object containing either True or False
dict() Creates a dictionary object from the specified keys and values
float() Returns an object of the `float` class that represent a floating point number.
ANKUR 41
L.J. GANDHI BCA COLLEGE, MODASA UNIT:2 BCA-601-PYTHON
issubclass() Checks if the specified class is the subclass of the specified subclass.
open() Opens the file (if possible) and returns the corresponding file object.
print() prints the given object to the console or to the text stream file.
slice() Returns a portion of an iterable as an object of the slice class based on the
specified range.
str() Returns an object of the str class with the specified value.
ANKUR 42
L.J. GANDHI BCA COLLEGE, MODASA UNIT:2 BCA-601-PYTHON
Python lambda
A function without a name is called ‘anonymous function’.
So far, the functions we wrote were defined using the keyword ‘def’, but anonymous
functions are not defiend using ‘def’.
They are defined using the keyword lambda and hence they are also called ‘Lambda
function’.
def square(x):
return x*x
For example, below lambda function also returns square of a given value just like the above.
lambda x : x*x
Example : Python program to create a lambda function that returns a square value
f = lambda x: x*x # write lambda function.
value = f(5) # call lambda function
print('Square of 5 = ’, value) # display result
Output :
square of 5 = 25
Output :
Sum = 11.55
There are two methods we can use with lambda function named as filter( ) and map( ).
ANKUR 43
L.J. GANDHI BCA COLLEGE, MODASA UNIT:2 BCA-601-PYTHON
Example : A Python program using filter() to filter out even numbers from a list.
# filter() function that returns even numbers from a list
def is_even(x):
if x%2 == 0:
return True
else:
return False
Output :
[10, 46, 70]
Output :
[10, 46, 70]
ANKUR 44
L.J. GANDHI BCA COLLEGE, MODASA UNIT:2 BCA-601-PYTHON
Output :
[1, 4, 9, 16, 25]
Output :
[1, 4, 9, 16, 25]
ANKUR 45
L.J. GANDHI BCA COLLEGE, MODASA UNIT:2 BCA-601-PYTHON
Now, we will create our own module by the name ‘employee’ and store the function da(),
hra(), pf() and itax() in that module, we can also store classes and variable also.
So for create our module type the following code and save the file as ‘employee.py’.
def hra(basic):
hra = basic * 15/100
return hra
def pf(basic):
pf = basic * 12/100
return pf
def itax(gross):
tax = gross*0.1
return tax
ANKUR 46
L.J. GANDHI BCA COLLEGE, MODASA UNIT:2 BCA-601-PYTHON
The another way of import the employee module as: from employee import *
In this case, all the functions of the employee module is referenced and we can refer to them
without using the module name, simply as: da(), hra(), pf() and itax().
Now see the following program, where we are using the ‘employee’ module and calculating
the gross and net salaries of an employee.
Example : A Python program that uses the functions of employee module and
calculates the gross and net salaries of an employee.
# using employee module to calculate gross and net salaries of an employee
from employee import *
Output :
Enter basic salary = 15000
Your gross salary = 29250
your net salary = 24525
ANKUR 47