0% found this document useful (0 votes)
3 views68 pages

03012025123656 Pm

The document provides an overview of Python operators and control statements, detailing various types of operators including arithmetic, assignment, comparison, logical, bitwise, identity, and membership operators. It also covers control statements such as if, if-else, nested if, elif, for loops, and while loops, explaining their syntax and usage with examples. The content is aimed at teaching Python programming concepts to students in a structured manner.

Uploaded by

cabogen976
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views68 pages

03012025123656 Pm

The document provides an overview of Python operators and control statements, detailing various types of operators including arithmetic, assignment, comparison, logical, bitwise, identity, and membership operators. It also covers control statements such as if, if-else, nested if, elif, for loops, and while loops, explaining their syntax and usage with examples. The content is aimed at teaching Python programming concepts to students in a structured manner.

Uploaded by

cabogen976
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 68

Python Programming(2301CS404)

Unit-02.1
Python
Operators

Prof. Shruti R. Maniar


Computer Engineering
Department
Darshan Institute of Engineering & Technology, Rajkot
[email protected]
 Looping
Outline
Arithmetic operators
Assignment operators
Comparison operators
Logical operators
Identity operators
Membership operators
Bitwise operators
Operators in Python
 Operators are used to perform operations on variables and values.
 We can segregate python operators in following groups :
 Arithmetic operators
 Assignment operators
 Comparison operators
 Logical operators
 Bitwise operators
 Identity operators
 Membership operators

Prof. Shruti R. Maniar # 2301CS404 (PP) Unit- 2 3


Arithmetic Operators
 Arithmetic Operators can be used with numeric values or variables to
perform common mathematical operations.
 Note : Consider A = 10 and B = 3
Operator Description Example Output
+ Addition A+B 13
- Subtraction A-B 7
3.3333333333333
/ Division A/B
335
* Multiplication A*B 30
% Modulus return the remainder A%B 1
// Floor division returns the quotient A // B 3
10 * 10 * 10 =
** Exponentiation A ** B
1000
 Imp. Point: Python does not support pre/post increment(++)/decrement(--) operators

Prof. Shruti R. Maniar # 2301CS404 (PP) Unit- 2 4


Assignment Operators
 Assignment Operators are used to assign values to variables.
 Note : Consider A = 3, B = 5 and C = 0
Operator Description Example Output
= Assign C=A+B 8
+= Add and Assign A+=B 8
-= Subtract and Assign A-=B -2
*= Multiply and Assign A*=B 15
/= Divide and Assign A/=B 0.6
%= Modulus and Assign A%=B 3
//= Divide(floor) and Assign A//=B 0
**= Power and Assign A**=B 243

Prof. Shruti R. Maniar # 2301CS404 (PP) Unit- 2 5


Relational Operators
 Relational Operators are used for comparing the values. It either returns
True or False according to the condition.
 Note : Consider A = 9, B = 5
Operator Description Example Output
> Greater than A>B True
< Less than A<B False
== Equal to A == B False
!= Not Equal to A != B True
>= Greater than or equal to A >= B True
<= Less than or equal to A <= B False

Prof. Shruti R. Maniar # 2301CS404 (PP) Unit- 2 6


Logical Operators
 Logical Operators are used to perform logical operations on the values of
variables. The value is either True or False. We can figure out the
conditions by the result of the truth values.
 Note : Consider A = 10 and B = 3
Operator Description Example Output
Returns True if both statements are
and
true
A > 5 and B < 5 True
Returns True if one of the
or
statements is true
A > 5 or B > 5 True
Negate the result, returns True if the
not
result is False
not ( A > 5 ) False

Prof. Shruti R. Maniar # 2301CS404 (PP) Unit- 2 7


Bitwise Operators
 The Bitwise Operators are used to perform bitwise calculations on
integers. The integers are first converted into binary and then operations
are performed on bit by bit, hence the name Bitwise Operators. Then the
result is returned in decimal format.
 Note : Consider A = 10(binary - 1010) and B = 4(binary - 0100)
Operator Description Example Output
& Bitwise AND A&B 0
| Bitwise OR A|B 14
~ Bitwise NOT ~A -11
^ Bitwise XOR A^B 14
>> Bitwise right shift A>>1 5
<< Bitwise left shift A<<1 20

Prof. Shruti R. Maniar # 2301CS404 (PP) Unit- 2 8


Example
Example.py
1 x , y = 5,2 Output
2 a,b = True,False x // y = 2
3
x ** y = 25
4 #Arithmetic operator
5 print('x // y =',x//y) x y = 10 4
6 print('x ** y =',x**y) x >= y is True
7 x <= y is False
9 #Assignemnt Operator x and y is False
10 x+=5 # x = 10 x or y is True
11 y+=2 # y = 4 not x is False
12 print('x y =',x,y)
x & y is 0
13
14 #Comparison Operator
x | y is 14
15 print('x >= y is',x>=y)
16 print('x <= y is',x<=y)
17
18 #Logical Operator
19 print('x and y is',a and b)
20 print('x or y is',a or b)
21 print('not x is',not a)
22
23 #Bitwise Operators
24 print('x & y is',x & y)
25 print('x | y is',x | y)

Prof. Shruti R. Maniar # 2301CS404 (PP) Unit- 2 9


Identity & Membership Operators
 Identity Operator
 Note : consider A = [1,2], B = [1,2] and C=A
Operat Exampl
Description Output
or e
Returns True if both variables are the A is B False
is
same object A is C True
Returns True if both variables are A is
is not
different object
True
not B
 Membership Operator
 Note : consider A = 2 and B = [1,2,3]
Operat Examp
Description Output
or le
Returns True if a sequence with the
in
specified value is present in the object
A in B True
Returns True if a sequence with the
A not
not in specified value is not present in the object False
in B

Prof. Shruti R. Maniar # 2301CS404 (PP) Unit- 2 10


Example
Example.py
1 x2 = 'Hello' Output
2 y2 = 'Hello' x2 is y2 = True
3 x3 = [1,2,3] x3 is y3 = True
4 y3 = x3 x2 is not y2 = False
5 'H' in x = True
6 x = 'Hello world' 'hello' not in x = True
7 y = {1:'a',2:'b'} 5 in z = True
9 z = [1,2,3,4,5] 1 in y = True
10
11 # Identity Operator
12 print("x2 is y2 = ",x2 is y2)
13 print("x3 is y3 = ",x3 is y3)
14 print("x2 is not y2 =",x2 is not y2)
15
16 # Membership Operator
17 print("'H' in x = ", 'H' in x)
18 print("'hello' not in x = ",'hello' not in x)
19 print("5 in z = ", 5 in z)
20 print("1 in y = ",1 in y)

Prof. Shruti R. Maniar # 2301CS404 (PP) Unit- 2 11


Python Programming(2101CS405)

Unit-02.2
Conditional and
Looping
Statements
Prof. Shruti R. Maniar
Computer Engineering
Department
Darshan Institute of Engineering & Technology, Rajkot
[email protected]
 Looping
Outline
If statement
if-else statement
nested if statement
elif statement
For loop statement
While loop statement
break
continue
pass keywords
Introduction
 The statements that help us to control the flow of execution in a program
called control statements.
 There are two types of control statements.
 Branching Statement :
 The statements that help us to select some statements for execution and skip other
statements.
 These statements are also called as decision making statements because they
make decision based on some condition and select some statements for execution.
 If statement
 if-else statement
 nested if statement
 elif statement
 Looping statements:
 The statements that help us to execute set of statements repeatedly are called as
looping statements.
 For loop statement
 Prof.
While loop
Shruti R. statement
Maniar # 2301CS404 (PP) Unit- 2 14
If statement
 if statement is written using the if keyword followed by condition and
colon(:) .
 Code to execute when the condition is true will be ideally written in the
next line with Indentation (white space).
 Python relies on indentation to define scope in the code (Other
programming languages often use curly-brackets for this purpose).
Syntax if statement ends with :
1 if some_condition :
2 # Code to execute when condition is true
Indentation (tab/whitespace) at the
beginning

ifdemo.py Output
1 x = 10 1 X is greater than 5
2
3 if x > 5 :
4 print("X is greater than 5"
)

Prof. Shruti R. Maniar # 2301CS404 (PP) Unit- 2 15


If else statement
 This is basically a “two-way” decision statement. This is used when we
must choose between two alternatives.
Syntax
1 if some_condition :
2 # Code to execute when condition is true
3 else :
4 # Code to execute when condition is false

ifelsedemo.p
y Output
1 x = 3 1 X is less than 5
2
3 if x > 5 :
4 print("X is greater than 5"
5 )
6 else :
print("X is less than 5")

Prof. Shruti R. Maniar # 2301CS404 (PP) Unit- 2 16


Example of if else
Example1.py Output
1 # Program checks if the number is positive or Enter Number = 5
2 negative Positive number
3 num = int(input("Enter Number="))
4 if num >= 0:
5 print("Positive number")
6 else:
print("Negative number")

Example2.py Output
1 # Program checks if the number is Odd or Even Enter Number = 4
2 num = int(input("Enter Number=")) Positive number
3 if num % 2 == 0:
4 print("Even number")
5 else:
6 print("Odd number")

Prof. Shruti R. Maniar # 2301CS404 (PP) Unit- 2 17


Nested if statement
 An if-else statement is written within another if-else statement is called
nested
Syntax
if statement.
1 if some_condition1 : Output
2 if some_condition2 : Enter a Number = 4
3 # Code to execute when condition is Positive number
4 true
5 else :
# Code to execute when condition is
false
Example1.py
1 num = float(input("Enter a number: "))
2 if num >= 0:
3 if num == 0:
4 print("Zero")
5 else:
6 print("Positive number")
7 else:
9 print("Negative number")

Prof. Shruti R. Maniar # 2301CS404 (PP) Unit- 2 18


Example
Example1.py
Output
1 # find maximum number from three
2 number Enter A=10
3 a = int(input("Enter A=")) Enter B=9
4 b = int(input("Enter B=")) Enter C=2
5 c = int(input("Enter C=")) Greater = 10
6
7 if a>b:
8 if a>c:
9 g=a
10 else:
11 g=c
12 else:
13 if b>c:
14 g=b
15 else:
16 g=c
17
print("Greater = ",g)

Prof. Shruti R. Maniar # 2301CS404 (PP) Unit- 2 19


If, elif and else statement
 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 a block can have only one else block, but it can have multiple elif
blocks.
 This statement is alternative for nested if statement to overcome the
complexity problem involved in nested if statement.

Prof. Shruti R. Maniar # 2301CS404 (PP) Unit- 2 20


If, elif and else statement
Syntax
1 if some_condition_1 :
2 # Code to execute when condition 1 is true
3 elif some_condition_2 :
4 # Code to execute when condition 2 is true
5 else :
6 # Code to execute when both conditions are false

ifelifdemo.py Output
1 x = 10 1 X is greater than 5
2
3 if x > 12 :
4 print("X is greater than 12
5 ")
6 elif x > 5 :
7 print("X is greater than 5"
8 )
else :
print("X is less than 5")

Prof. Shruti R. Maniar # 2301CS404 (PP) Unit- 2 21


Example
Example1.py Output
1 # Python Program to find Student Grade Please enter English Marks: 50
2 english = float(input(" Please enter English Marks: "))
3 math = float(input(" Please enter Math score: ")) Please enter Math score: 50
4 computers = float(input(" Please enter Computer Marks: ")) Please enter Computer Marks: 50
5 physics = float(input(" Please enter Physics Marks: ")) Please enter Physics Marks: 50
6 chemistry = float(input(" Please enter Chemistry Marks: "))
7 Please enter Chemistry Marks:
8 total = english + math + computers + physics + chemistry 50
9 percentage = (total / 500) * 100 Total Marks = 250.00
10
11 print("Total Marks = %.2f" %total) Marks Percentage = 50.00
12 print("Marks Percentage = %.2f" %percentage) E Grade
13
14 if(percentage >= 90):
15 print("A Grade")
16 elif(percentage >= 80):
17 print("B Grade")
18 elif(percentage >= 70):
19 print("C Grade")
20 elif(percentage >= 60):
21 print("D Grade")
22 elif(percentage >= 40):
23 print("E Grade")
24 else:
25 print("Fail")

Prof. Shruti R. Maniar # 2301CS404 (PP) Unit- 2 22


For loop in python
 Many objects in python are iterable, meaning we can iterate over every
element in the object.
 such as every elements from the List, every characters from the string etc..
 We can use for loop to execute block of code for each element of iterable
Syntax
object. For loop ends with :
1 for temp_item in iterable_object :
2 # Code to execute for each object in iterable
Indentation (tab/whitespace) at the
beginning

fordemo1. fordemo2.
Output : Output :
py py
1 my_list = [1, 2, 3, 4] 1 1 my_list = [1,2,3,4,5,6,7,8,9] 2
2 for list_item in my_list : 2 2 for list_item in my_list : 4
3 print(list_item) 3 3 if list_item % 2 == 0 : 6
4 4 print(list_item) 8

Prof. Shruti R. Maniar # 2301CS404 (PP) Unit- 2 23


range() function
 The range() function returns a sequence of numbers, starting from 0 by
default, and increments by 1 (by default), and stops before a specified
number.
Syntax
1 range(start, stop, step)

Example1.py Example2.py Example3.py Example4.py


1 x = range(3, 6) 1 x = range(3, 20, 1 x = range(20) 1 x =
2 for n in x: 2 2) 2 for n in x: 2 reversed(range(20))
3 print(n) 3 for n in x: 3 print(n) 3 for n in x:
print(n) print(n)
Output Output Output Output
3 3 0 19
4 5 1 18
5 . . . . . . . . .
19 19 0

Prof. Shruti R. Maniar # 2301CS404 (PP) Unit- 2 24


For loop (tuple unpacking)
 Sometimes we have nested data structure like List of tuples, and if we
want to iterate with such list we can use tuple unpacking.
withouttupleunapacking
withtupleunpacking.py
.py
1 my_list = [(1,2,3), (4,5,6), (7,8,9) 1 my_list = [(1,2,3), (4,5,6), (7,8,
2 ] 2 9)]
3 for list_item in my_list : 3 for a,b,c in my_list :
print(list_item[1]) print(b)
This
Output : Output :
technique
2 2
is known
5 5
as tuple
8 8
unpacking

Prof. Shruti R. Maniar # 2301CS404 (PP) Unit- 2 25


For loop with else
 The else block just after for/while is executed only when the loop is NOT
terminated by a break statement.
Example1.py Example2.py
1 for i in range(1, 4): 1 for i in range(1, 4):
2 print(i) 2 print(i)
3 else: 3 break
4 print("No Break") 4 else: # Not executed as there is a
5 break
print("No Break")

Output Output
1 1
2
3
No Break

Prof. Shruti R. Maniar # 2301CS404 (PP) Unit- 2 26


Example
Example1.py
Output
1 #odd numbers between 1 to n
2 num = int(input("Enter Number = ")) Enter Number = 5
3 for i in range(1,num+1): 1
4 if i % 2 != 0: 3
5 print(i) 5

Example2.py
Output
1 #series 1 + 4 + 9 + 16 + 25 + 36 + ...n
2 num = int(input("Enter Number = ")) Enter Number = 10
3 sum = 0 Sum= 385
4 for i in range(1,num+1):
5 sum = sum + i**2
6 print("Sum=",sum)

Prof. Shruti R. Maniar # 2301CS404 (PP) Unit- 2 27


Example
Example3.py
Output
1 # Find factorial of the given number
2 num = int(input("Enter Number = ")) Enter Number = 5
3 fact = 1 Factorial = 120
4 for i in range(1,num+1):
5 fact = fact * i
6 print("Factorial =", fact )

Example4.py
Output
1 #series 1 – 2 + 3 – 4 + 5 – 6 + 7 ... n
2 num = int(input("Enter Number = ")) Enter Number = 10
3 sum = 0 Sum= -5
4 for i in range(1,num+1):
5 if i % 2 == 0:
6 sum = sum - i
7 else:
8 sum = sum + i
9 print("Sum=",sum)

Prof. Shruti R. Maniar # 2301CS404 (PP) Unit- 2 28


While loop
 While loop will continue to execute block of code until some condition
remains True.
 For example,
 while felling hungry, keep eating
Syntax
while have internet pack available, keep watching videos
while loop ends with :
1 while some_condition :
2 # Code to execute in loop
Indentation (tab/whitespace) at the Output :
withelse.p X is
beginning
y
1 x = 5 greater
whiledemo.py 2 while x < 3 : than 3
1 x = 0
Output :
3 print(x)
2 while x < 3 : 0 4 x += 1 # x+
3 print(x) 1 5 + is invalid in python
4 x += 1 # x+ 2 6 else :
+ is invalid in python print("X is greater than 3")

Prof. Shruti R. Maniar # 2301CS404 (PP) Unit- 2 29


Example
Example1.py
Output
1 #odd numbers between 1 to n
2 num = int(input("Enter Number = ")) Enter Number = 5
3 i=0 1
4 while(i<=num): 3
5 if i % 2 != 0: 5
6 print(i)
7 i+=1

Example2.py
Output
1 #series 1 + 4 + 9 + 16 + 25 + 36 + ...n
2 num = int(input("Enter Number = ")) Enter Number = 10
3 sum = i = 0 Sum= 385
4 while(i<=num):
5 sum = sum + i**2
6 i+=1
7 print("Sum=",sum)

Prof. Shruti R. Maniar # 2301CS404 (PP) Unit- 2 30


Exercise programs
 Do Following programs using for and while loop.
 WAP to find out sum of first and last digit of a given number
 WAP to find whether the given number is prime or not.
 WAP to find out prime numbers between given two numbers
 WAP to print given number in reverse order.
 WAP to check whether the given number is Armstrong or not.
 WAP to find the sum of 1 + (1+2) + (1+2+3) + (1+2+3+4)+ …+(1+2+3+4+….+n).

Prof. Shruti R. Maniar # 2301CS404 (PP) Unit- 2 31


break keyword
 Breaks out of the current closest enclosing loop.
 Break Statement is a loop control statement that is used to terminate the
loop.
 As soon as the break statement is encountered from within a loop, the
loop iterations stop there, and control returns from the loop immediately
to the first statement after the loop.
 Basically, break statements are used in situations when we are not sure
Syntax
about
1 break
the actual number of iterations for the loop or we want to terminate
the loop based on some condition.
breakdemo.py
1 for temp in range(5) : Output :
2 if temp == 2 : 0
3 break 1
4
5 print(temp)

Prof. Shruti R. Maniar # 2301CS404 (PP) Unit- 2 32


continue keyword
 Goes to the top of the current closest enclosing loop.
 Continue statement is a loop control statement that forces to execute the
next iteration of the loop while skipping the rest of the code inside the
loop for the current iteration only i.e.
 When the continue statement is executed in the loop, the code inside the
loop following the continue statement will be skipped for the current
iteration and the next iteration of the loop will begin.
Syntax
1 continue

continuedemo
.py Output :
1 for temp in range(5) : 0
2 if temp == 2 : 1
3 continue 3
4
4
5 print(temp)

Prof. Shruti R. Maniar # 2301CS404 (PP) Unit- 2 33


pass keyword
 Does nothing at all, will be used as a placeholder in conditions where you
don’t want to write anything.
 The pass statement is a null statement. But the difference between pass
and comment is that comment is ignored by the interpreter whereas pass
is not ignored.
Syntax
1 pass

passdemo.py Output :
1 for temp in range(5) : (nothing)
2 pass

Prof. Shruti R. Maniar # 2301CS404 (PP) Unit- 2 34


Python Programming(2101CS405)

Unit-02.3
Functions

Prof. Shruti R. Maniar


Computer Engineering
Department
Darshan Institute of Engineering & Technology, Rajkot
[email protected]
 Looping
Outline
Creating function
DOCSTRING
Types of arguments
Calling function
return statement
Scope of Variables
Lambda expression
Recursion
Functions in python
 Creating clean repeatable code is a key part of becoming an effective
programmer.
 A function is a block of code which only runs when it is called.
 In Python
Syntax a function is defined using the def keyword:
ends with :
def function_name() :
#code to execute when function is called
Indentation (tab/whitespace) at the
beginning Output :
Functiondemo
hello world
.py =====================
1 def seperator() : =========
2 print('==============================') from darshan college
3 =====================
4 print("hello world") =========
5 seperator()
rajkot
6 print("from darshan college")
7 seperator()
8 print("rajkot")

Prof. Shruti R. Maniar # 2301CS404 (PP) Unit- 2 37


Function (cont.)
 There are two kinds of functions in Python.
 Built-in Functions : Functions that are provided as part of Python - input(),
print()...
 User Defined Functions : Functions that we define ourselves and then use.
 Then we treat the built-in function names as "new" reserved words (i.e. we
avoid them as variable names)
 In Python a function is some reusable code that takes arguments(s) as
input, does some computation and then returns a result(s)
 We call/invoke the function by using the function name, parenthesis and
arguments in an expression
Functiondemo Argumen
Function
.py ts
name 1 a = max(2,90)
2 print(a)

Prof. Shruti R. Maniar # 2301CS404 (PP) Unit- 2 38


Function Names
 Use a naming scheme, and use it consistently (camel case syntax).
 For all names, avoid abbreviations, unless they are both standardized and
widely used.
 The name should describe the data’s meaning rather than its type (e.g.,
amount_due rather than money),
 Functions and methods should have names that say what they do or what
they return (depending on their emphasis), but never how they do it—
since that might change.
 All three functions below return the index position of the first occurrence
of a name in a list of names, starting from the given starting index and
using an algorithm that assumes the list is already sorted.
Functiondemo
.py
1 def find(l, s, i=0): # BAD
2 def linear_search(l, s, i=0): # BAD
3 def first_index_of(sorted_name_list, name, start=0): # GOOD

Prof. Shruti R. Maniar # 2301CS404 (PP) Unit- 2 39


Function (cont.) (DOCSTRING & return)
 Doc string helps us to define the documentation about the function within
theSyntax
function itself.
Enclosed within triple quotes
def function_name() :
'''
DOCSTRING: explains the function
INPUT: explains input
OUTPUT: explains output
'''
#code to execute when function is call
ed

 Unlike conventional source code comments, the docstring should describe


what the function does, not how.
 The docstrings can be accessed using the __doc__ method of the object or
using the help function.
Help.py
1 Function_name. __doc__

Prof. Shruti R. Maniar # 2301CS404 (PP) Unit- 2 40


Function Types
 Four kinds of functions can be created in Python: global functions, local
functions, lambda functions, and methods.
 Global function
 Global objects (including functions) are accessible to any code in the same module
(i.e., the same .py file) in which the object is created.
 Local functions
 (also called nested functions) are functions that are defined inside other functions.
These functions are visible only to the function where they are defined;
 They are especially useful for creating small helper functions that have no use
elsewhere.
 Lambda functions
 Lambda functions are expressions, so they can be created at their point of use;
 however, they are much more limited than normal functions.
 Methods
 Methods are functions that are associated with a particular data type and can be
used only in conjunction with the data type (when we cover object-oriented
programming.)
Prof. Shruti R. Maniar # 2301CS404 (PP) Unit- 2 41
Exercise
 WAP to count simple interest using function.
 WAP to find maximum number from given two numbers using function.
 WAP that defines a function exchange to interchange the values of two
variables, say x and y.

Prof. Shruti R. Maniar # 2301CS404 (PP) Unit- 2 42


Function Arguments
 A function by using the following types of formal arguments:
 Required/Positional arguments
 Keyword arguments
 Default arguments
 Variable-length arguments
 Required arguments/ Positional arguments
 Required arguments are the arguments passed to a function in correct positional
order.
 During a function call, values passed through arguments should be in the order of
parameters in the function definition. Output
Demo.py
1 def add_number(n1,n2): Sum = 5
2 print("Sum = ", n1+n2) Sum = 8
3
4 add_number(2,3)
5 add_number(3,5)

Prof. Shruti R. Maniar # 2301CS404 (PP) Unit- 2 43


Function Arguments(cont.)
 Keyword arguments
 When you use keyword arguments in a function call, the caller identifies the
arguments by the parameter name.
 This allows you to skip arguments or place them out of order because the Python
interpreter is able to use the keywords provided to match the values with
parameters.
 Functions can also be called using keyword arguments of the form kwarg=value
 During a function call, values passed through arguments need not be in the order of
parameters in the function definition. This can be achieved by keyword arguments.
Demo.py Output
1 def subtract_number(n1,n2): Subtraction = 10
2 print("Subtraction = ", n1-n2) Subtraction = -10
3
4 subtract_number(20,10)
5 subtract_number(n2=20,n1=10) Keyword Arguments

Prof. Shruti R. Maniar # 2301CS404 (PP) Unit- 2 44


Function Arguments(cont.)
 Default arguments
 A default argument is an argument that assumes a default value if a value is not
provided in the function call for that argument.
 Default arguments are values that are provided while defining functions.
 The assignment operator = is used to assign a default value to the argument.
 Default arguments become optional during the function calls.
 If we provide a value to the default arguments during function calls, it overrides the
default value.
 Default arguments should follow non-default arguments.
Demo.py Output
1 def add_number(n1,n2 = 10): Sum = 5
2 print("Sum = ", n1+n2) Sum = 13
3
4 add_number(2,3)
5 add_number(3)

Prof. Shruti R. Maniar # 2301CS404 (PP) Unit- 2 45


Function Arguments(cont.)
 Variable-length arguments
 Variable-length arguments are also known as arbitrary arguments. If we don’t know
the number of arguments needed for the function in advance, we can use arbitrary
arguments.
 There are two types of variable length arguments
 Arbitrary positional arguments
 You may need to process a function for more arguments than you specified while
defining the function.
 These arguments are called variable-length arguments Tuple representing
and are not named in the
Syntax
function definition, unlike required and default arguments. variable length
def functionname([formal_args,] *var_args_tuple ): arguments
#code to execute when function is called

 An asterisk (*) is placed before the variable name that will hold the values of all non
keyword variable arguments.
 This tuple remains empty if no additional arguments are specified during the function
call
Prof. Shruti R. Maniar # 2301CS404 (PP) Unit- 2 46
Function Arguments(cont.)
 Arbitrary positional arguments example

Demo.py Output
1 def add_number(n1,*n): Sum = 2
2 sum = n1 Sum = 40
3 for i in n:
4 sum = sum + i
5 print("Sum = ", sum)
6
7 add_number(2)
8 add_number(10,10,10,10)

Prof. Shruti R. Maniar # 2301CS404 (PP) Unit- 2 47


Function Arguments(cont.)
 Arbitrary keyword arguments
 For arbitrary positional argument, a double asterisk (**) is placed before a parameter
in a function which can hold keyword variable-length arguments.

Demo.py Output
1 def add_Number(**a): Sum= 7
2 sum = 0 ('a', 4)
3 sum = a['a'] + a['b'] ('b', 3)
4 print("Sum=",sum) ('c', 4)
5 for i in a.items(): {'a': 4, 'b': 3, 'c': 4}
6 print(i)
7 print(a)
8
9 add_Number(a=4,b=3,c=4)

Prof. Shruti R. Maniar # 2301CS404 (PP) Unit- 2 48


Pass by reference vs value
 In call by value method, the value of the actual parameters is copied into
the formal parameters.
 In call by reference, the address of the variable is passed into the function
call as the actual parameter.
 In python value is passed as “Call by Object Reference” or “Call by
assignment”.
 When we pass whole numbers, strings or tuples to a function, the passing
is like call-by-value because you can not change the value of the
immutable objects being passed to the function.
 Whereas passing mutable objects can be considered as call by reference
because when their values are changed inside the function, then it will
also be reflected outside the function.

Prof. Shruti R. Maniar # 2301CS404 (PP) Unit- 2 49


Pass by reference vs value
CallByValue.p CallByReferenc
y e.py
1 # Call by Value 1 # Call by Reference
2 def modifiy_String(s): 2 def add_more(list):
3 s = "Darshan University" 3 list.append(50)
4 print("Inside Function:", s) 4 print("Inside Function:", list)
5 5
6 6
7 str = "Darshan" 7 list = [1,2,3,4,5]
8 modifiy_String(str) 8 add_more(list)
9 print("Outside Function:",str) 9 print("Outside Function:",list)

Output Output
Inside Function: Darshan University Inside Function: [1, 2, 3, 4, 5,
Outside Function: Darshan 50]
Outside Function: [1, 2, 3, 4, 5,
50]

Prof. Shruti R. Maniar # 2301CS404 (PP) Unit- 2 50


Pass by reference vs value
def printA(a): def printList(a):
a = 3 a.append(3)

x=2 x= [1,2]
printA(x) printList(x)
print("A = ",x) print("List",x)

Call by Value Call by Reference

X a X a

2 2 [1,2]

Prof. Shruti R. Maniar # 2301CS404 (PP) Unit- 2 51


return Statement
 return statement : return allows us to assign the output of the function
to a new variable, return is use to send back the result of the function,
instead of just printing it out.
 A return statement is used to end the execution of the function call. The
statements after the return statements are not executed.
 If the return statement is without any expression, then the special value
None is returned.
returnDemo.p
 In python
y we can return multiple values from function using object, tuple,
1 def
list, add_number(n1,n2) :
Dictionary.
2 return n1 + n2
3 Output :
4 sum1 = add_number(5,3) 8
5 sum2 = add_number(6,1) 7
6 print(sum1)
7 print(sum2)

Prof. Shruti R. Maniar # 2301CS404 (PP) Unit- 2 52


return Multiple values
returndemo.p
Output
y
1 def test(): (1, 2, 3)
2 a=1 2
3 b=2 a, b, c= 1 2 3
4 c=3
5 return a,b,c # return multiple values
6
7 x = test()
8 a,b,c = test()
9 print(x)
10 print(x[1])
11 print("a, b, c=",a,b,c)

Prof. Shruti R. Maniar # 2301CS404 (PP) Unit- 2 53


Exercise
 WAP that define a function to find factorial of given number.
 WAP that defines a function which returns 1 if the number is prime
otherwise return 0.
 WAP to generate Fibonacci series of N given number using function name
fibbo.
 WAP that defines a function to add first n numbers.

Prof. Shruti R. Maniar # 2301CS404 (PP) Unit- 2 54


Scope of Variables
 All variables in a program may not be accessible at all locations in that
program. This depends on where you have declared a variable.
 The scope of a variable determines the portion of the program where you
can access a particular identifier. There are two basic scopes of variables
in Python:
 Global variables
 Local variables
 Variables that are defined inside a function body have a local scope, and
those defined outside have a global scope.
 This means that local variables can be accessed only inside the function in
which they are declared.
 whereas global variables can be accessed throughout the program body
by all functions.
 When we call a function, the variables declared inside it are brought into
scope.
Prof. Shruti R. Maniar # 2301CS404 (PP) Unit- 2 55
Scope of Variables (cont.)
Local.py Output
1 total = 0 Inside the function local total : 30
2 def sum( arg1, arg2 ): Outside the function global total : 0
3 total = arg1 + arg2
4 print ("Inside the function local total : ",
5 total)
6 return total;
7 # Now you can call sum function
8 sum( 10, 20 );
print ("Outside the function global total : ",
total)
Global.py Output
1 total = 0 Inside the function local total : 30
2 def sum( arg1, arg2 ): Outside the function global total : 30
3 global total
4 total = arg1 + arg2
5 print ("Inside the function local total : ",
6 total)
7 return total;
8 # Now you can call sum function
9 sum( 10, 20 );
print ("Outside the function global total : ",
total)
Prof. Shruti R. Maniar # 2301CS404 (PP) Unit- 2 56
Lambda Function
 We can use the lambda keyword to create small anonymous functions.
 These functions are called anonymous because they are not declared in
the standard manner by using the def keyword.
 Lambda forms can take any number of arguments but return just one
value in the form of an expression. They cannot contain multiple
expressions.
 An anonymous function cannot be a direct call to print because lambda
requires an expression.
 Lambda functions have their own local namespace and cannot access
variables other than those in their parameter list and those in the global
namespace.
 Although it appears that lambda's are a one-line version of a function,
they are not equivalent to inline statements in C or C++

Prof. Shruti R. Maniar # 2301CS404 (PP) Unit- 2 57


Lambda Function (cont.)
Syntax
1 lambda arg1,arg2..argN: expression

 The parameters are optional, and if supplied they are normally just
comma- separated variable names, that is, positional arguments.
 Lambda functions accept all kinds of arguments, just like normal def
function
 The expression can not contain branches or loops (although conditional
expressions are allowed), and cannot have a return statement. The result
of a lambda expression is an anonymous function.
 When a lambda function is called it returns the result of computing the
Example.py
expression as its
1 sum = lambda result.arg1 +
arg1,arg2:
2 arg2
print("Total",sum(5,5))
Outp
ut
Total 10

Prof. Shruti R. Maniar # 2301CS404 (PP) Unit- 2 58


Lambda Function (cont.)
Outpu
Cube.py
t
1 def cube(y): 125
2 return y*y*y 125
3 lambda_cube = lambda y: y*y*y
4
5 # using the normally defined function
6 print(cube(5))
7 # using the lambda function
8 print(lambda_cube(5))

Outpu
WithIfElse.py
t
1 # Example of lambda function using if-else 2
2 Max = lambda a, b : a if(a > b) else b
3 print(Max(1, 2))

call.py Outpu
1 # Lambda functions can be Immediately Invoked t
9
2
print((lambda x: x*x)(3))

Prof. Shruti R. Maniar # 2301CS404 (PP) Unit- 2 59


Exercise
 WAP to find square of given number using lambda expression.
 WAP to find simple interest using lambda function.
 WAP to make simple calculator using lambda expression.

Prof. Shruti R. Maniar # 2301CS404 (PP) Unit- 2 60


Map
 map() function returns a map object(which is an iterator) of the results
after applying the given function to each item of a given iterable (list,
tuple etc.)
Syntax
1 map(fun, iterable)

Outpu
demo1.py
t
1 def addition(n): [1, 4, 9,
2 return n * n 16]
3
4 numbers = [1, 2, 3, 4]
5 result = list(map(addition, numbers))
6 # result = list(map(lambda n:n*n,numbers))
7 print(result)

demo2.py Outpu
1 strdata = ["Darshan","University"] t
[7, 10]
2 lengthdata = list(map(len,strdata))
3 print(lengthdata)

Prof. Shruti R. Maniar # 2301CS404 (PP) Unit- 2 61


Functional Programming Tools: filter and reduce
 To find out items based on a test function we can use a Filter.
 For example, the following filter call picks out items in a sequence that are
divide by 2:
demo1.py Outpu
1 lista = [1,2,3,4,5,6,7,8,9,10] t
[2, 4, 6, 8, 10]
2 ans = list(filter(lambda x: x % 2 == 0 ,lista))
3 print(ans)

Prof. Shruti R. Maniar # 2301CS404 (PP) Unit- 2 62


Functional Programming Tools: filter and reduce
 Apply functions to pairs of items and running results (reduce(fun,seq)).
 In the first step, the first two elements of the sequence are chosen, and the result is
obtained.
 The result is then stored after applying the same function to the previously obtained
result and the number just succeeding the second element.
 This process is repeated until there are no more elements in the container.
 The final result is returned and printed to the console.
demo1.py Outpu
1 from functools import reduce t
55
2 lista = [1,2,3,4,5,6,7,8,9,10]
3 ans = reduce(lambda a,b : a+b,lista)
4 print(ans)

demo2.py Outpu
1 from functools import reduce t
10
2 lista = [1,2,3,4,5,6,7,8,9,10]
3 ans = reduce(lambda a,b : a if a>b else b,lista)
4 Print(ans)

Prof. Shruti R. Maniar # 2301CS404 (PP) Unit- 2 63


Recursion
 Any function which calls itself is called recursive function and such
function calls are called recursive calls.
 Recursion cannot be applied to all problems, but it is more useful for the
tasks that can be defined in terms of a similar subtask.
 It is idea of representing problem a with smaller problems.
 Any problem that can be solved recursively can be solved iteratively.
 When recursive function call itself, the memory for called function
allocated and different copy of the local variable is created for each
function call.
 Some of the problem best suitable for recursion are
 Factorial
 Fibonacci
 Tower of Hanoi

Prof. Shruti R. Maniar # 2301CS404 (PP) Unit- 2 64


Properties of Recursion
 A recursive function can go infinite like a loop. To avoid infinite running of
recursive function, there are two properties that a recursive function must
have.
 Base Case or Base criteria
 It allows the recursion algorithm to stop.
 A base case is typically a problem that is small enough to solve directly.
 Progressive approach
 A recursive algorithm must change its state in such a way that it moves forward to
the base case.

Prof. Shruti R. Maniar # 2301CS404 (PP) Unit- 2 65


Recursion - factorial example
 The factorial of a integer n, is product of

Recursive trace
n * (n-1) * (n-2) * …. * 1
 Recursive definition of factorial Final Ans 5 *24 = 120
 n! = n * (n-1)!
Fact(5)
 Example
return 4 * 6 = 24
 3! = 3 * 2 * 1 call
 3! = 3 * (2 * 1) Fact(4)
 3! = 3 * (2!) return 3 * 2 = 6
call
Fact(3)
return 2 * 1 = 2
call
Fact(2)
return 1
call
Fact(1)

Prof. Shruti R. Maniar # 2301CS404 (PP) Unit- 2 66


Examples
Factorial.py Output
1 def recursive_factorial(n): Enter the number=5
2 if n == 1: Factorial of number 5 = 120
3 return n
4 else:
5 return n * recursive_factorial(n-1)
6 # recursive function call
7
8 # user input
9 num = int(input("Enter the number="))
10 print("Factorial of number", num, "=",
recursive_factorial(num))
fibonacci.py Output
1 def r_fibonacci(n): Fibonacci series:
2 if n <= 1: 0
3 return n 1
4 else: 1
-
5 return(r_fibonacci(n-1) + r_fibonacci(n-2))
-
6 n = 8 13
7 print("Fibonacci series:")
8 for i in range(n):
9 print(r_fibonacci(i))

Prof. Shruti R. Maniar # 2301CS404 (PP) Unit- 2 67


Exercise
 Write a program to find factorial of a given number using recursion.
 WAP to convert decimal number into binary using recursion.
 WAP to use recursive calls to evaluate F(x) = x – x3/3! + x5/5! – x7/7! + …
+ xn/n!

Prof. Shruti R. Maniar # 2301CS404 (PP) Unit- 2 68

You might also like