0% found this document useful (0 votes)
2 views

python unit 2

The document provides an overview of conditional statements and control flow in Python, including if, if-else, and nested if statements. It also covers loop control statements such as break, continue, and pass, as well as for and while loops with examples. The document aims to teach decision-making and looping constructs in Python programming.

Uploaded by

bhoibazigar007
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

python unit 2

The document provides an overview of conditional statements and control flow in Python, including if, if-else, and nested if statements. It also covers loop control statements such as break, continue, and pass, as well as for and while loops with examples. The document aims to teach decision-making and looping constructs in Python programming.

Uploaded by

bhoibazigar007
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 48

Ankur

(Python [601] – Unit 2)


COLLEGE ==> MATRUSHRI L.J.
GANDHI BCA COLLEGE, MODASA
L.J. GANDHI BCA COLLEGE, MODASA UNIT:2 BCA-601-PYTHON

Conditional statement in python


 There comes situations in real life when we need to make some decisions and based on these
decisions, we decide what should we do next.
 Similar situations arise in programming also where we need to make some decisions and
based on these decisions we will execute the next block of code.
 Decision-making statements in programming languages decide the direction of the flow of
program execution.
 Following are some control statement which we used in python.
 If statement
 If else statement
 if...elif...else Statement or The elif statement
 Comprehension statement (multiple condition) or Nested if statement

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

Example : Program to check even no.


num = int(input("enter the number = "))
if num%2 == 0:
print("Number is even")

Output :
enter the number = 10
Number is even

Example : Program to print the largest of the three numbers.


a = int(input("Enter a = "));
b = int(input("Enter b = "));
c = int(input("Enter c = "));

if a>b and a>c:


print("a is largest");

if b>a and b>c:


print("b is largest");

if c>a and c>b:


print("c is largest");

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

Short Hand if statement


 Whenever there is only a single statement to be executed inside the if block then shorthand if
can be used.
 The statement can be put on the same line as the if statement.
 Syntax: if condition: statement

Example: Python if shorthand


i = 10
if i < 15 : print("i is less than 15")

Output :
i is less than 15

ANKUR 4
L.J. GANDHI BCA COLLEGE, MODASA UNIT:2 BCA-601-PYTHON

If…else statement in python


 The if statement alone tells us that if a condition is true it will execute a block of statements
and if the condition is false it won’t.
 But what if we want to do something else if the condition is false. Here comes the else
statement.
 We can use the else statement with if statement to execute a block of code when the
condition is false.
 Syntax :
if test expression:
Body of if
else:
Body of else

 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

Example : Program to checks if the number is positive or negative


num = 3
if num >= 0:
print("Positive or greater than Zero")
else:
print("Negative number")

Output :
Positive or greater than Zero

Example : Program to check whether a person is eligible to vote or not.


age = int (input("Enter your age = "))
if age>=18:
print("You are eligible to vote !!");
else:
print("Sorry! you have to wait !!");

Output :
Enter your age = 90
You are eligible to vote !!

Example : Program to check whether a number is even or not.


num = int(input("enter the number = "))
if num%2 == 0:
print("Number is even...")
else:
print("Number is odd...")

Output :
enter the number = 10
Number is even

ANKUR 6
L.J. GANDHI BCA COLLEGE, MODASA UNIT:2 BCA-601-PYTHON

Short Hand if-else statement


 This can be used to write the if-else statements in a single line where there is only one
statement to be executed in both if and else block.
 Syntax: statement_when_True if condition else statement_when_False

Example: Python if else shorthand


i = 10
print(True) if i < 15 else print(False)

Output :
True

ANKUR 7
L.J. GANDHI BCA COLLEGE, MODASA UNIT:2 BCA-601-PYTHON

If…elIf…else statement In python


OR
The elif statement
 Here, a user can decide among multiple options.
 The if statements are executed from the top down and as soon as one of the conditions
controlling the if is true, the statement associated with that if is executed, and the rest of the
ladder is bypassed.
 If none of the conditions is true, then the final else statement will be executed.
 Syntax :
if test expression:
Body of if
elif test expression:
Body of elif
else:
Body of else

 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

Example : Program to checks if the number is positive or negative or zero


num = 3.4

if num > 0:
print("Positive number")

elif num == 0:
print("Zero")

else:
print("Negative number")

Output :
Positive number

Example : Program to check number is equel or not.


number = int(input("Enter the number = "))

if number == 10:
print("number is equals to 10")

elif number == 50:


print("number is equal to 50");

elif number == 100:


print("number is equal to 100");

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

Example : Program to check grade


marks = int(input("Enter the marks = "))

if marks > 85 and marks <= 100:


print("Congrats ! you scored grade A ...")

elif marks > 60 and marks <= 85:


print("You scored grade B + ...")

elif marks > 40 and marks <= 60:


print("You scored grade B ...")

elif (marks > 30 and marks <= 40):


print("You scored grade C ...")

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

Nested If…else in Python


 We can have a if...elif...else statement inside another if...elif...else statement. This is called
nesting in computer programming.
 Any number of these statements can be nested inside one another.
 Indentation is the only way to figure out the level of nesting.
 They can get confusing, so they must be avoided unless necessary.

Example : Program to checks if the number is positive or negative or zero


num = float(input("Enter a number = "))

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

Loop control statement in Python


 Control statements in python are used to control the flow of execution of the program based
on the specified conditions.
 Python supports 3 types of control statements such as,
1) Break Statement
2) Continue Statement
3) Pass Statement

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':

# break the loop as soon it sees 'e' or 's'


if letter == 'e' or letter == 's':
break

print ('Current Letter :', letter)

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':

# Prints all letters except 'e' and 's'


if letter == 'e' or letter == 's':
continue

print ('Current Letter :', letter)

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

For loop in Python


 The for loop in Python is used to iterate the statements or a part of the program several times.
 Syntax :
for iterating_var in sequence:
statement(s)
 The for loop flowchart

Example : Iterating string using for loop


str = "Python"
for i in str:
print(i)

Output:
P
y
t
h
o
n

ANKUR 15
L.J. GANDHI BCA COLLEGE, MODASA UNIT:2 BCA-601-PYTHON

Example : Program to print the table of the given number.


list = [1,2,3,4,5,6,7,8,9,10]
n=5
for i in list:
c = n*i
print(c)

Output :
5
10
15
20
25
30
35
40
45
50

Example : Program to print the sum of the given list.


list = [10,30,23,43,65,12]
sum = 0
for i in list:
sum = sum+i
print("The sum is = ",sum)

Output :
The sum is = 183

ANKUR 16
L.J. GANDHI BCA COLLEGE, MODASA UNIT:2 BCA-601-PYTHON

For loop Using range() function


 The range() function is used to generate the sequence of the numbers.
 If we pass the range(10), it will generate the numbers from 0 to 9.
 Syntax: range(start,stop,step size)

Example : Program to print numbers in sequence.


for i in range(10):
print(i,end = ' ')

Output :
0123456789

Example : Program to print table of given number.


n = int(input("Enter the number "))
for i in range(1,6):
c = n*i
print(n,"*",i,"=",c)

Output :
Enter the number 10
10 * 1 = 10
10 * 2 = 20
10 * 3 = 30
10 * 4 = 40
10 * 5 = 50

Nested for loop in python


 Python allows us to nest any number of for loops inside a for loop.
 The inner loop is executed n number of times for every iteration of the outer loop.
 Syntax :
for iterating_var1 in sequence: # outer loop
for iterating_var2 in sequence: # inner loop
# block of statements
# Other statements

ANKUR 17
L.J. GANDHI BCA COLLEGE, MODASA UNIT:2 BCA-601-PYTHON

Example : Program of * pyramid.


# User input for number of rows
rows = int(input("Enter the rows = "))
# Outer loop will print number of rows
for i in range(0,rows+1):
# Inner loop will print number of Astrisk
for j in range(i):
print("*",end = '')
print()

Output :
Enter the rows = 5
*
**
***
****
*****

Example : Program of number pyramid.


rows = int(input("Enter the rows = "))
for i in range(0,rows+1):
for j in range(i):
print(i,end = '')
print()

Output :
Enter the rows = 5
1
22
333
4444
55555

ANKUR 18
L.J. GANDHI BCA COLLEGE, MODASA UNIT:2 BCA-601-PYTHON

Using else statement with for loop


 Unlike other languages like C, C++, or Java, Python allows us to use the else statement with
the for loop which can be executed only when all the iterations are exhausted.
 Here, we must notice that if the loop contains any of the break statement then the else
statement will not be executed.
Example : 1
for i in range(0,5):
print(i)
else:
print("for loop completely exhausted, since there is no break.")

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

while loop in Python


 The Python while loop allows a part of the code to be executed until the given condition
returns false.
 Syntax :
while expression:
statements
 The while loop flowchart

Example : Program to print 1 to 10 using while loop


i=1
#The while loop will iterate until condition becomes false.
While(i<=10):
print(i)
i=i+1

Output :
0123456789

ANKUR 20
L.J. GANDHI BCA COLLEGE, MODASA UNIT:2 BCA-601-PYTHON

Example : Program to print table of given numbers.


i=1
number=0
b=9
number = int(input("Enter the number : "))
while i<=10:
print("%d X %d = %d \n" %(number,i,number*i))
i = i+1

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

Infinite while loop


 If the condition is given in the while loop never becomes false, then the while loop will never
terminate, and it turns into the infinite while loop.

Example : Infinite while loop


while (1):
print("Hi! we are inside the infinite while loop")

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

Using else with while loop


 The else part is executed if the condition in the while loop evaluates to False.
 The while loop can be terminated with a break statement and in such cases, the else part is
ignored.
 Hence, a while loop's else part runs if no break occurs and the condition is false.

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

while counter < 3:


print("Inside loop")
counter = counter + 1
else:
print("Inside else")

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.

Syntax to Create an Array in Python


arrayName = array.array(type code for data type, [array,items])

Example
import array as myarray
abc = myarray.array('d', [2.5, 4.9, 6.7])

 The following is the explanation about the terms.


 Identifier : specify a name like usually, you do for variables
 Module : Python has a special module for creating arrays, called “array” – you must
import it before using it
 Method : the array module has a method for initializing the array. It takes two
arguments, type code, and elements.
 Type Code : specify the data type using the type codes available
 Elements : specify the array elements within the square brackets.

 Commonly used type codes are listed as follows:


Code C Type Python Type Min Bytes
b signed char int 1
B unsigned char int 1
h signed short int 2
H unsigned short int 2
i signed int int 2
I unsigned int int 2
u py_unicode unicode character 2
l signed long int 4
L unsigned long int 4
f float float 4
d double float 8

ANKUR 24
L.J. GANDHI BCA COLLEGE, MODASA UNIT:2 BCA-601-PYTHON

Creating Python Arrays


 An array can be declared in various ways and different languages.
 The important points that should be considered are as follows:
 Index starts with 0.
 We can access each element via its index.
 The length of the array defines the capacity to store the elements.
 To create an array, we need to import the array module.

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])

Accessing array elements


 You can access any array item or element by using its index.
 Syntax : arrayName[indexNum]

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

Slicing Python Arrays


 We can access a range of items in an array by using the slicing operator.

Example
import array as arr

numbers_list = [2, 5, 62, 5, 42, 52, 48, 5]


numbers_array = arr.array('i', numbers_list)

print(numbers_array[2:5]) # 3rd to 5th


print(numbers_array[:-5]) # beginning to 4th
print(numbers_array[5:]) # 6th to end
print(numbers_array[:]) # beginning to end

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])

Add elements in array


 Arrays are mutable, and their elements can be changed in a similar way like lists.
 Python array insert operation enables you to insert one or more items into an array at the
beginning, end, or any given index of the array.
 This method expects two arguments index and value as arrayName.insert(index, value).

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

Modify elements in array


 In Python, arrays are mutable. They can be modified by syntax Object_name[index]=value.

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])

Delete elements in array


 With this operation, you can delete one item from an array by value.
 This method accepts only one argument as arrayName.remove(value)
 After running this method, the array items are re-arranged, and indexes are re-assigned.

Example
import array as myarray
first = myarray.array('b', [2, 3, 4])
first.remove(3)
print(first) # Output : array('b', [2, 4])

Search and get index of array


 With this operation, you can search for an item in an array based on its value.
 This method accepts only one argument as : arrayName.index(value)
 This operation will return the index of the first occurrence of the mentioned element.

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])

Count the occurrence of a Value in Array


 You can also count the occurrence of elements in the array using the array.count(x) syntax.

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

Importing array module in python


 There are three ways to import the array module into our program.

 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)

#call the function


sum(10, 15) # call first time
sum(1.5, 10.75) # call second time

Output :
Sum 25
Sum 12.25

ANKUR 31
L.J. GANDHI BCA COLLEGE, MODASA UNIT:2 BCA-601-PYTHON

Returning result from a function


 We can return a result or output from the function using a ‘return’ statement in the body of
the function as shown below.
 return c # returns c value out of function
 return 100 #returns 100
 return x, y, z #returns 3 values
 When a function does not return any result, we don’t need to write the return statement in the
body of the function.

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

#call the function


x = sum(10, 15)
print('The sum is:’, x)

y = sum(1.5, 10.75)
print('The sun is:’, y)

Output :
The sun is: 25
The sun is: 12.25

Example : A function to test whether a number is even or odd.


#a function to test whether a number is even or odd
def even_odd(num):
if num % 2 = = 0:
print(num," is even")
else:
print (num," is odd").

ANKUR 32
L.J. GANDHI BCA COLLEGE, MODASA UNIT:2 BCA-601-PYTHON

# call the function


even_odd(12)
even_odd(13)

Output:
12 is even
13 is odd

Returning multiple values from a function


 A function return a single value in the programming language like C or Java, But in Python,
a function can return multiple values.
 When a function calculates multiple results and wants to return the results, we can use the
return statement as:
return a, b, c # Here, 3 values named as ‘a’, ’b’, and ‘c’ are returned
 To grab these values, we can use three variables at the time of calling the function as:
x, y, z = function(values)

Example : A python program to understand how a function returns two values


def sum_sub(a,b) :
c=a+b
d=a-b
return c, d

# get the results from the sum_sub() function.


x, y = sum_sub (10, 5)

# display the results


print("Result of addition: ", x) # Result of addition: 15
print("Result of subtraction: ", y) # Result of subtraction: 5

ANKUR 33
L.J. GANDHI BCA COLLEGE, MODASA UNIT:2 BCA-601-PYTHON

Pass by object reference in python


 In the languages like C and Java, when we pass values to a function, we think about two
ways:
1. Pass by value or call by value
2. Pass by reference or call by reference
 Pass by value represents that a copy of the variable value is passed to the function and any
modification to that value will not reflect outside the function.
 Pass by reference represents sending the reference or memory address of the variable to the
function.
 The variable value is modified by the function through memory address and hence the
modified value will reflect outside the function also.
 In Python, to know a location of an object in heap (temporary), we can use id() function that
gives identity number of an object.
 This number may change from computer to computer as it is computed depending on the
available memory location where object ‘10’ is stored in the computer.

Example : A Python program to pass an integer to a function and modify it.


# passing an integer to a function
def modify(x):
x=15
print(x, id (x)) # Output : 15 1617805096

# call modify() and pass x


x= 10
modify(x)
print(x, id (x)) # Output : 10 1617805016

ANKUR 34
L.J. GANDHI BCA COLLEGE, MODASA UNIT:2 BCA-601-PYTHON

Example : A Python program to pass a list to a function and modify it.


# passing a list to a function
def modify (lst):
lst.append(9)
print(lst, id(lst))

# call modify() and pass lst


lst = [1,2,3,4]
modify (lst)
print(lst, id(lst))

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))

#call modify and pass 1st


lst = [1,2,3,4]
modify (lst)
print(lst, id(lst))

Output :
[10, 11, 12] 29505976
[1, 2, 3, 4] 29505016

 You can easily understand above program by this figure:

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)

# call the function


x = 10; y = 15
sum(x, y) # x. y are actual arguments.

 The actual arguments used in a function call are of 4 types as below:


 Positional arguments
 Keyword arguments
 Default arguments
 Variable length argument

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

Example : A Python program to understand the positional arguments of a function.


# positional arguments demo
def attach(s1, s2):
s3 = s1 + s2
print("Total string:” +s3)

# call attach() and pass 2 strings


attach('New', ‘York') # positional arguments

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.

Example : A Python program to understand the keyword arguments of a function.


# keyword arguments demo
def grocery (item, price):
print('Item = %s’ % item)
print('Price = %.2f' % price)

# call grocery() and pass 2 arguments


grocery(item=’Sugar’, price=50.75) #keyword arguments
grocery (price=88.00, item='oil') # keyword arguments

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.

Example : A Python program to understand the default arguments in a function.


# Default arguments demo
def grocery (item, price = 40.00):
print('Item = %s’ % item)
print('Price = %.2f' % price)

# call grocery() and pass arguments


grocery(item=’Sugar’, price=50.75) #pass 2 arguments
grocery (item='sugar') # default value for price is used

Output :
Item= sugar
Price = 50.75
Item = sugar
Price = 40.00

ANKUR 39
L.J. GANDHI BCA COLLEGE, MODASA UNIT:2 BCA-601-PYTHON

4. Variable length Arguments


 Sometimes, the programmer does not know how many values a function may receive.
 In that case, the programmer cannot decide how many arguments to be given in the function
definition.
 For example, if the programmer is writing a function to add two numbers, he can write:
add(a, b) But, the user who is using this function may want to use this function to find sum
of three numbers.
 In that case, there is a chance that the user may provide 3 arguments to this function as
add(10,15,20) and at that time add() function will fail and error will be displayed.
 If the programmer wants to develop a function that accept ‘n’ arguments, that is also possible
in Python and for this purpose, a variable length argument is used in the function definition.
 A variable length argument is an argument that can accept any number of values.

 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))

# call add() and pass arguments


add(5, 10)
add(5, 10, 20, 30)

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

Inbuilt Functions list in python


Method Description
abs() Returns the absolute value of the given number.

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).

bin() Converts an integer number to a binary string prefixed with '0b'.

bool() Converts a value to the bool class object containing either True or False

bytearray() Returns a bytearray object which is an array of the given bytes

bytes() Returns an immutable object of the bytes class.

classmethod() Transforms a method into a class method

complex() Returns a complex number.

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.

getattr() Returns the value of the attribute of an object.

hex() Converts an integer number to a lowercase hexadecimal string prefixed with


"0x".

help() It displays the documentation of modules, functions, classes, keywords etc.

id() Returns an identity of an object.

int() Returns an integer object constructed from a number.

input() Allows user to input values.

ANKUR 41
L.J. GANDHI BCA COLLEGE, MODASA UNIT:2 BCA-601-PYTHON

isinstance() Checks if the object is an instance of the specified class or not.

issubclass() Checks if the specified class is the subclass of the specified subclass.

len() Returns the length of the object.

list() Returns a list from an iterable passed as arguement.

max() Returns the largest value from the specified iterable.

min() Returns the lowest value from the specified iterable.

next() Returns the next item from the iterator.

oct() Converts an integer to octal string prefixed with "0o".

open() Opens the file (if possible) and returns the corresponding file object.

pow() Returns the specified exponent power of a number.

print() prints the given object to the console or to the text stream file.

reversed() Returns the reversed iterator of the given sequence.

slice() Returns a portion of an iterable as an object of the slice class based on the
specified range.

sorted() Returns a sorted list from the items in an iterable.

str() Returns an object of the str class with the specified value.

sum() Returns the total of elements.

tuple() Creates an empty tuple.

type() Returns the type of the specified object.

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

Example: A lambda function to calculate the sum of two numbers.


f = lambda x, y: x+y # write lambda function
result = f(1.55, 10) # call lambda function
print('Sum = ’, result) # display result

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

Using Lambdas with filter() Function


 The filter() function is useful to filter out the elements of a sequence depending on the result
of a function.
 We should supply a function and a sequences to the filter() function as filter(function,
sequence) where the function represents a function name that may return either True or
False and ‘sequence’ represents a list, string or tuple.
 The ‘function’ is applied to every element of the ‘sequence’ and when the function returns
True, the element is extracted otherwise it is ignored.

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

#let us take a list of numbers


lst = [10, 23, 45, 46, 70, 99]

#call filter() with is_even() and lst


Lst1 = list(filter(is_even, lst))
print(lst1)

Output :
[10, 46, 70]

Example :A lambda that returns even numbers from a list.


# a lambda function that returns even numbers from a 1ist
lst = [10, 23, 45, 46, 70, 99]
lst1 = list(filter (lambda x: (x%2 == 0), lst))
print(lst1)

Output :
[10, 46, 70]

ANKUR 44
L.J. GANDHI BCA COLLEGE, MODASA UNIT:2 BCA-601-PYTHON

Using Lambdas with map() Function


 The map() function is similar to filter() function but it acts on each element of the sequence
and changes the elements.
 The format of map() function is map(function, sequence)
 The ‘function’ performs a specified operation on all of the elements of the sequence and the
modified elements are returned which can be stored in another sequence.

Example : A Python program to find squares of elements in a list


# map() function that gives squares
def squares(x):
return x*x

#let us take a list of numbers


lst = [1, 2, 3, 4, 5]

#call map() with squares and lst


lst1 = list(map(squares, lst))
print(lst1)

Output :
[1, 4, 9, 16, 25]

Example: A lambda function that returns squares of elements in a list


# lambda that returns squares
lst = [1, 2, 3, 4, 5]
lst1 = list(map(lambda x: x*x, lst))
print(lst1)

Output :
[1, 4, 9, 16, 25]

ANKUR 45
L.J. GANDHI BCA COLLEGE, MODASA UNIT:2 BCA-601-PYTHON

Creating our own module in python


 A module represents a group of classes, methods, functions and variables.
 While we are developing software, there may be several classes, methods, and functions.
 We should first group them depending on their relationship into various modules and later
use these modules in the other program.
 It means, when a module is developed, it can be reused in any program that needs that
module.
 In Python, we have several built-in modules like sys, io, time etc. and just like these module
we can also create our own modules and use them whenever we need them.
 Once a module is created, any programmer in the project team can use that module so
modules make our work easy and fast.

 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’.

# save this code as employee.py


def da(basic):
da = basic * 80/100
return da

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

 To import the module, we can write: import employee.


 In this case, we have to refer the functions by adding the module name as: employee.da(),
employee.hra(), employee.pf(), employee.itax().

 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 *

# calculate gross salary of employee by taking basic


basic = float(input('Enter basic salary = '))

# calculate gross salary


gross = basic+da(basic)+hra(basic)
print('your gross salary = ’, gross)

#calculate net salary


net = gross - pf(basic)-itax(gross)
print (‘your net salary = ‘, net))

Output :
Enter basic salary = 15000
Your gross salary = 29250
your net salary = 24525

ANKUR 47

You might also like