Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 113

U18CSI2201 - PYTHON PROGRAMMING

UNIT - II

CONTROL STATEMENTS AND


FUNCTIONS IN PYTHON
Learning Objectives
• After undergoing this course the student able
to
CO1: Classify and make use of python programming elements to solve and debug
simple logical problems.(K4,S3)
CO2: Experiment with the various control statements in Python.(K3,S2)

CO3: Develop Python programs using functions and strings.(K3,S2)

CO4: Analyze a problem and use appropriate data structures to solve it.(K4,S3)

CO5: Develop python programs to implement various file operations and exception
handling.(K3,S2)
Source of Content
• http://nptel.ac.in
• https://www.edx.org/course/introduction-to
-python-fundamentals-1
• https://www.edx.org/course/computing-in-p
ython-ii-control-structures-0
Grading

CAT (2 Exams each 20%) 40%

5 Assignments (4% at each) 20%

End semester exam 40%

Total 100%
CONTROL STATEMENTS
AGENDA
• Introduction
• (conditional) if
• (alternative) if-else
• Nested-if
• (chained conditional) if-elif-else
Decision Making Statements or Control
Statements
Python supports various conditional statements.
They are:
• (conditional) if
• (alternative) if-else
• Nested-if
• (chained conditional) if-elif-else
if statement
It is used to control the flow of execution of the statements and
also to test logically whether the condition is true or false.
Syntax:
if condition :
statement (s)

if the condition is true then the statement following the “if “ is


executed if it is false then the statement is skipped.
if statement
• The statement(s) must be indented at least one
space right of the if statement.
• If there is more than one statement after if, each
statement must be indented using same number of
spaces.
Example:
num = int(input(“Enter a number:”))
if num > 0:
print(num, "is a positive number.")

Output:
Enter a number: 3
3 is a positive number
Exercise
Write a program which prompts a user to enter
the radius of a circle. If the radius is greater than
zero then calculate and print the area and
circumference of the circle.
if-else statement
It is used to execute some statements when the condition is
true and execute some other statements when the condition
is false depending on the logical test.
Syntax:
if condition :
statement 1 (if the condition is true this statement will be executed)
else:
statement 2 (if the condition is false this statement will be executed)
if-else statement
Example:
num = int(input(“Enter a number:”))
if num >= 0:
print("Positive or Zero")
else:
print("Negative number")

Output:
Case 1:
Enter a number: -5
Negative number

Case2:
Enter a number: 3
Positive or Zero
Exercise
1.) Write a program to prompt the user to enter
two numbers. Find the greater number.

2.) Write a program to prompt the user to enter a


number. Find whether the given number is odd or
even.

3.) Write a program to test whether a number is


divisible by 5 or 7.
Nested if statements
• Any number of these statements can be nested
inside one another.
• Indentation is the only way to figure out the level of
nesting.
Syntax:

if condition 1:
if condition 2:
statement 1
else:
statement 2
else:
if condition 3:
statement 3
else:
statement 4
Nested if statements
Example:

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


if num >= 0:
if num == 0:
print("Zero")
else:
print("Positive number")
else: print("Negative number")

Output:
Case 1:
Enter a number: 5
Positive number

Case 2:
Enter a number: -1
Negative number

Case 3:
Enter a number: 0
Zero
Exercise
• Write a program to check whether a given
year is leap year or not using nested if
statements.
• Write a program to find the greatest of three
numbers using nested if statements.
if-elif-else statements
• When a series of decisions are involved we have to use more
than one if – else statement called as multiple if-elif-else.
• Multiple if-elif-else statements are much faster than a series
of if – else statements, since their structure is exited when
any one of the condition is satisfied.
Syntax:
if (condition_1) :
execute statement_1
elif (condition_2):
execute statement_2
elif (condition_3):
execute statement_3
----------------------
----------------------
elif (condition_n):
execute statement_n
else:
execute statement_x
if-elif-else statements
Example:
x = int(input("Enter x:"))
y = int(input("Enter y:"))
if(x < y):
st= "x is less than y"
elif (x == y):
st= "x is same as y"
else:
st="x is greater than y"
print(st)

Output:
Case 1: Case 2: Case 3:
Enter x: 5 Enter x: 2 Enter x: 5
Enter y: 5 Enter y: 5 Enter y: 3
x is same as y x is less than y x is greater than y
Output:
Four digit
Exercise
• Write a program to prompt a user to read the marks
of five subjects. Calculate the total marks and
percentage of the marks and display the message
according to the range of percentage given in table:
Percentage Message
Per > = 90 Distinction
Per > = 80 && Per < 90 First Class
Per > = 70 && Per < 80 Second Class
Per > = 60 && Per < 70 Third Class
Per < 60 Fail
• Write a program to prompt a user to enter a
day of the week. If the entered day of the
week is between 1 and 7, then display the
respective name of the day.

• Write a program that prompts a user to enter


two different numbers. Perform basic
arithmetic operations based on the choices.
Conditional Expressions
• It offers one-line code to evaluate the first expression
if the condition is true, otherwise it evaluates the
second expression.
Syntax:
Expression 1 if condition else Expression2

• It first evaluates the condition; if it


returns True, expression1 will be evaluated to give
the result, otherwise expression2.

• Only one expression will be executed.


Conditional Expressions
• Example1:
age = int(input("Enter age:"))
print('kid' if age < 18 else 'adult')
• Example2:
age = int(input("Enter age:"))
print('kid' if age < 13 else 'teenager' if age < 18 else 'adult')
This example is same as:
if age < 18:
if age < 13:
print('kid')
else:
print('teenager')
else:
print('adult')
Exercise
• Write a program using conditional
expressions to print greatest of two
numbers.
• Write a program using conditional
expressions to check if the number is odd
or even.
Quiz
What would be the output from the following Python
program ?

num=10
if num==20:
print("apple")
print("grapes") Output:
vegetable
print(“vegetable")
Quiz
What will be the output of the following
program?
if (20<1) and (1<-1):
print("Hello")
elif (20>10) or False: Output:
Hi
print('Hi')
else:
print('Bye')
Summary
• Python supports various decision statements,
such as if, if-else, multi-way if-elif-else
statements.
• Python does not have a ternary operator. It
uses a conditional expression instead.
LOOP CONTROL STATEMENTS
Agenda
• while loop
• range( ) function
• for Loop
• Nested Loops
• break statement
• continue statement
• pass statement
The while loop
• It executes a sequence of statements repeatedly as long
as the condition is true.
• Syntax:
while test-condition:
statement(s)
• test-condition is a boolean expression
• Colon(:) must follow the test condition
• The statements within the while loop will be executed till
the condition is true.
• When the condition is false, the execution goes out of
the loop
• Note: All statements within the while block must be
indented with the same number of spaces.
The while loop
• Flowchart for while loop:
The while loop
Example:
Write a program to print the numbers from one
to five using the while loop.
count =0
while count<=5: Output:
count = 0
print("count = ", count) count = 1
count = count + 1 count = 2
count = 3
count = 4
count = 5
The while loop
Example:
Write a program to add 10 consecutive numbers
starting from1 using the while loop.

count =0 Output:
Sum of first 10 Numbers = 55
sum = 0
while count<=10:
sum = sum + count
count = count + 1
print("Sum of first 10 Numbers = ", sum)
Example:
Write a program to print the factorial of a number
using the while loop.

num = int (input("Enter a number: "))


fact = 1
count = 1
Output:
while count <= num: Enter a number: 5
fact = fact * count Factorial of 5 is: 120
count = count + 1

print("Factorial of ",num, " is: ", fact)


Check a number is a palindrome
n=int(input("Enter a number:"))
rev=0
c=n
while(n!=0):
num=n%10 Note:
rev=rev*10+num 1%10 = 1
n=n//10 1//10 = 0
print("Reverse is", rev)

if(c==rev):
print("Palindrome")
else:
Exercise
• Write a program to find the sum of the
digits of a given number.
• Write a program to display the reverse of
the number entered.
• Write a program to check whether the
number entered is an Armstrong number
or not. i.e., 153 = 13 + 53 + 33
The range( ) Function
• range() is a built in function
• Used to generate list of integers
• Has one, two or three parameters
• Last two parameters are optional
• General form:
range(begin, end, step)
 begin – first beginning number in the sequence at
which the list starts
 end – limit - last number in the sequence
 step – difference between each number in the
sequence
Examples of range()
>>>list(range(1,6))
[1, 2, 3, 4, 5]

>>>list(range(1,10,2))
[1, 3, 5, 7, 9]
Example Output
range(1,5) [1, 2, 3, 4]
range(1,20,2) [1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
range(5) [0, 1, 2, 3, 4]
range(5,0,-1) [5, 4, 3, 2, 1]
range(5,0,-2) [5, 3, 1]
range(1,10,2) [1, 3, 5, 7, 9]
range(-4,4) [-4, -3, -2, -1, 0, 1, 2, 3]
range(-4,4,2) [-4, -2, 0, 2]
range(0,1) [0]
range(1,1) []empty
range(0) []empty
The for loop
• for loop iterates through a sequence of objects.
• Iterates through each value in a sequence
Syntax:
for var in sequence:
statement(s)

 keywords for and in are used to iterate the sequence


of values
 the variable var takes on each consecutive value in
the sequence
 the statements in the body of the loop are executed
once for each value
Code Output
for i in 'hello': h
print(i) e
l
l
o

for i in range(1,6): 1
print(i) 2
print("End of the program") 3
4
5
End of the program

print("The capital letters A to Z are: The capital letters A to Z


") are:
for i in range(65,91): ABCDEFGHIJKLMNO
PQRSTUVWXYZ
print(chr(i), end=" ")
The for loop
Exercise:
• Write a program to print squares of first five
numbers.
• Write a program to print the numbers from 1
to 10 in reverse order.
• Write a program to print the even numbers in
the specified range and find their sum.
• Write a program to print the fibonacci
numbers.
Nested Loops
• Loops within the loops or when one loops is inserted
completely within another loop, then it is called nested
loop.
Syntax:
Nested for loop:
for iterating_var in sequence:
for iterating_var in sequence:
statements(s)
statements(s)
Nested while loop:
while expression:
while expression:
statement(s)
statement(s)
Nested Loops - Example
Program to print multiplication table from 1 to 5:

for i in range(1,11,1): Output:


for j in range(1,6,1): 12345
2 4 6 8 10
print(i*j, end = " ")
3 6 9 12 15
print() 4 8 12 16 20
5 10 15 20 25
6 12 18 24 30
7 14 21 28 35
8 16 24 32 40
9 18 27 36 45
10 20 30 40 50
Nested Loops
Example:
Program to print pattern of numbers:
1
1 2 Execution steps:
1 2 3 Iteration 1: i=1, num=2
2 2 3 4 j in range(1,2), print 1
3 2 3 4 5
Iteration 2: i=2, num=3
j in range(1,3), print 1 2
Iteration 3: i=3, num=4
Program:
j in range(1,4), print 1 2 3
num = 1
Iteration 4: i=4, num=5
for i in range(1,6): j in range(1,5), print 1 2 3 4
num = num + 1 Iteration 5: i=5, num=6
for j in range(1,num): j in range(1,6), print 1 2 3 4 5
print(j, end = " ")
Nested Loops
Exercises:
1. Write a program to display the pattern of stars as follows:
* * *
* *
*
2. Write a program to display the symbols in pattern as follows:
$
# #
$ $ $
# # # #
The break statement
• The break statement terminates the loop
containing it. Control of the program flows to
the statement immediately after the body of
the loop.
• If break statement is inside a nested loop
(loop inside another loop), break will
terminate the innermost loop.
• Syntax
break
The break statement
• Flowchart of break
The break statement
• The working of break statement in for
loop and while loop is shown below.
The break statement
Example:
for val in "string":
if val == "i":
break
print(val)
print("The end")
Output:
s
t
r
The end
The break statement
Exercise:
Write a program to check whether entered
number is prime or not.
The continue statement
• The continue statement is used to skip the rest
of the code inside a loop for the current
iteration only.
• Loop does not terminate but continues on
with the next iteration.
Syntax
continue
The continue statement
Flowchart of continue
The continue statement
The working of continue statement in for and
while loop is shown below.
The continue statement
Example:
for val in "string":
if val == "i":
continue
print(val)
print("The end")
Output:
s
t
r
n
g
The end
The continue statement

Exercise:
Write a program to read a string from the user
and print the string after removing spaces.
Difference between break and continue functions

Break Continue
Exits from current block or Skips the current iteration
loop. and also skips the
remaining statements
within the body.

Control passes to the next Control passes at the


statement. beginning of the loop.

Terminates the loop. Never terminates the loop.


The pass statement
• pass is a null statement.
• The difference between a comment and a pass
statement in Python is that,
– interpreter ignores a comment entirely.
– pass is not ignored.
• However, nothing happens when pass is
executed. It results into no operation (NOP).
Syntax:
pass
• used as a placeholder.

• if a loop or a function is not implemented , but


will be implemented in the future, it cannot
have an empty body. The interpreter would
complain. So, the pass statement is used to
construct a body that does nothing.
The pass statement
Example:
sequence = {'p', 'a', 's', 's'}
for val in sequence:
pass
Quiz
What is the output of the following:
i=1
while True:
if i%2 == 0:
break
print(i) d) 1 3 5 7 9 11 …
i += 2
a) 1
b) 1 2
c) 1 2 3 4 5 6 …
d) 1 3 5 7 9 11 …
Quiz
What is the output of the following?
True = False
while True:
print(True)
break d) error
a) True
b) False
c) None
d) error
Quiz
What does the following snippet print:

for i in range(11,16):
if i%2==0:
print('Jack')
Jill and Jack
elif i%3==0:
Jack
print('Jill')
Jill and Jack
elif i%2==0 and i%3==0:
Jack
print('Jack and Jill')
Jill
else:
print('Jill and Jack')
SUMMARY
• Loop is a process of executing a set of
statements for fixed number of times.
• Two types of loop control statements:
– for loop and while loop
• Break statement exits from the current block
or loop.
• Continue statement skips the current iteration
of the loop.
FUNCTIONS
FUNCTIONS
• A function is a self-contained block of one or
more statements that perform a special task
when called.
• Is a group of related statements that perform a
specific task.
• Help break our program into smaller and
modular chunks.
• Make the code more organized and manageable.
• Avoids repetition.
• Makes code reusable.
TYPES OF FUNCTIONS
• Built-in functions - Functions that are built into
Python. Functions that readily come with
Python are called built-in functions.
Eg. abs(), chr()

• User-defined functions - Functions defined by


the users themselves to do certain specific
task are referred as user-defined functions.
Example: User defined function
Advantages of user-defined functions
• User-defined functions help to decompose a
large program into small segments which
makes program easy to understand, maintain
and debug.
• Can be used to include the repeated codes
and execute when needed by calling that
function.
• Programmers working on large project can
divide the workload by making different
functions.
FUNCTIONS
Syntax :
def function_name(parameters):
statement(s)

A function definition consists of following components.


• Keyword def marks the start of function header.
• A function name is to uniquely identify it. Function naming follows the
same rules of writing identifiers in Python.
• Through parameters (arguments), pass values to a function. They are
optional.
• A colon (:) to mark the end of function header.
• One or more valid python statements that make up the function body.
Statements must have same indentation level (usually 4 spaces).
• An optional return statement to return a value from the function.
FUNCTIONS
Example 1:
Function definition:
def greet(name):
print("Hello, " + name + ". Good morning!")

Function call:
>>> greet('Paul')
Hello, Paul. Good morning!
FUNCTIONS
Example 1:
def display( ): #Function definition
print(“Good morning!")
display() #Function call

Output:
Good morning!
USE OF A FUNCTION – Avoid repetition and code reusability
sum = 0 def sum(x,y):
for i in range(1,26): s=0
sum=sum+i
print("Sum of integers from 1 to 25 is: for i in range(x,y+1):
",sum) s=s+i
print('Sum of integers
sum = 0
for i in range(50,76): from ',x,' to ',y,' is: ',s)
sum=sum+i
print("Sum of integers from 50 to 76 sum(1,25)
is: ",sum) sum(50,75)
sum = 0 sum(90,100)
for i in range(50,101):
sum=sum+i
print("Sum of integers from 50 to 100
is: ",sum)
Example: To find the factorial of a number
def fact(n): Output:
f=1
for i in range(1,n + 1): Enter a number: 5
f=f*i The factorial of 5 is 120
print("The factorial of",n,"is",f)
Enter a number: 8
The factorial of 8 is 40320
num = int(input("Enter a number: "))
fact(num) Enter a number: 10
num = int(input("Enter a number: ")) The factorial of 10 is
fact(num) 3628800
num = int(input("Enter a number: "))
fact(num)
FUNCTIONS
Positional Arguments:
• The parameters are assigned according to their position.
Example:
def display(name,age):
print("name = ", name," age = ",age)

display("John",25)
display(40,"Sachin")

Output:
name = John age = 25
name = 40 age = Sachin
FUNCTIONS
KEYWORD ARGUMENTS
• The parameter name can be used explicitly while calling.
• A keyword can be passed to a function by using its
corresponding parameter name rather than its position.
Example:
def display(name,age):
print("name= ", name," age= ",age)

display(age=40,name="Sachin")

Output:
name= Sachin age= 40
FUNCTIONS
PARAMETER WITH DEFAULT VALUES
• Parameters within a function’s definition can have default
values.
• Default value can be provided by using assignment (=) operator.
Example:
def display(name, age=20):
print("name= ", name," age= ",age)

display("John",25)
display("Sachin")
Output:
name= John age= 25
name= Sachin age= 20
The return statement
• The return statement is used to return a value
from the function.
• Also used to exit a function.
Syntax:
return [expression_list]
• This statement can contain expression which gets
evaluated and the value is returned.
• If there is no expression in the statement or
the return statement itself is not present inside a
function, then the function will return
the None object.
The return statement
Example:
def minimum(a,b):
if a<b:
return a
elif b<a:
return b
else:
return “Both numbers are equal”

print(minimum(100,85))

Output:
85
The return statement
Example:
def absolute_value(num):
if num >= 0:
return num
else:
return –num

print(absolute_value(2))
# Output: 2

print(absolute_value(-4))
# Output: 4
Returning multiple values
• It is possible to return multiple values.
Example 1:
def calc(n1, n2):
return n1+n2, n1-n2

print(calc(20,10))

Output:
(30, 10)
Returning multiple values
• It is possible to return multiple values.
Example 2:
def calc(n1, n2):
return n1+n2, n1-n2

sum,sub = calc(20,10)
print("Sum = ",sum,"Diff = ", sub)

Output:
Sum = 30 Diff = 10
Area of Circle using Functions
def calc(r):
return 3.14*r*r
x = (int(input('Enter the radius:')))
print(' The are of circle is',calc(x)) #X passed as
argument to calc()
Output
Enter the radius:5
78.5
LOCAL AND GLOBAL VARIABLES
• Variables declared inside a function are known as local
variables.
• Variables declared outside a function are known as global
variables.
Example:
def fun( ):
q=10 #local variable
print("q= ",q)
print("p= ",p)

p=20 #global variable


fun( )
LOCAL AND GLOBAL VARIABLES
Example:
def fun( ):
q=10 #local variable
print("p= ",p)

p=20 #global variable


fun( )
print("q= ",q) # NameError: name 'q' is not defined

# Local variable cannot be accessed outside the


function
LOCAL AND GLOBAL VARIABLES
Example:
# Local variable and global variable with the same name
def fun( ):
p=10 #local variable
print("p= ",p)

p=20 #global variable


fun( )
print(“p= ",p)

Output:
p= 10
p= 20
Exercise
• Write a program using functions to perform
arithmetic calculations.
• Write a function reverse_number() to return
the reverse of the number entered.
• Write a program using functions to find the
maximum of two numbers.
function reverse_number()
def reverse(n):
rev=0
while(n!=0):
num=n%10
rev=rev*10+num
n=n//10
return(rev)

n=int(input("Enter a number:"))
print(reverse(n))
Output
Enter the number:234
Recursive Functions
• A function is said to be recursive if a statement
within the body of the function
calc_factorial(4)
calls itself.
# 1st call with 4
Example: 4 * calc_factorial(3) # 2nd call with 3
4 * 3 * calc_factorial(2) # 3rd call with 2
4 * 3 * 2 * calc_factorial(1) # 4th call with 1
4*3*2*1 # return from 4th
def calc_factorial(x):
call as
if x == 1: number=1
return 1 4*3*2 # return from 3rd call
4*6 # return from 2nd call
else: 24 # return from 1st call
return (x * calc_factorial(x-1))

num = 4
print("The factorial of", num, "is", calc_factorial(num))
Exercise
• For a quadratic equation in the form of ax2+bx+c,
the discriminant is b2-4ac. Write a function to
compute the discriminant D, that returns the
following output depending on the discriminant
D.
• Write a program using recursion to find the sum
of numbers from 1 to n.
• Write a program to generate the fibonacci
numbers.
• A positive integer is entered through the
keyboard. Write a function factors(num) to
obtain the factors of the given numbers.
Quadratic equation Roots – Using Function
import math
def eval_Quadratic_Equa(a, b ,c, x):
d = (b**2) - 4*a*c
if d < 0:
print('The equation has no real solution')
elif d == 0:
x = (- b + math.sqrt(d))/ (2*a)
print(' This equation has one solution:',x)
else:
x1 = (-b - math.sqrt(d))/(2*a)
x2 = (-b + math.sqrt(d))/(2*a)
print(' Equation has two solutions: ',format(x1,'.2f'),' and ',format(x2,'.2f'))

a = float(input('Enter the value of a:'))


b = float(input('Enter the value of b:'))
c = float(input('Enter the value of c:'))
Factors of a given number
def factors(num):
print('Factors of ',num,' are as follows: ')
for x in range(1,num+1):
if num % x == 0:
print(x, end = ' ')
else:
pass
num = int(input('Please Enter the number:'))
factors(num)
Output
Please Enter the number:120
Factors of 120 are as follows:
Lambda Function
• Named after the Greek letter λ (lambda).
• Also known as anonymous functions.
• Is a function that is defined without a name.
• While normal functions are defined using
the def keyword, the anonymous functions are
defined using the lambda keyword.
Syntax:
Name=lambda(variables):code
•Such functions are not bound to a name.
•Only have a code to execute that is
associated with them.
Example:
cube=lambda x: x*x*x
print(cube(2))
Output:
8
Example:
double = lambda x: x * 2
print(double(5))
Output:
10

• lambda x: x * 2 is the lambda function.


• Here x is the argument and x * 2 is the expression that gets
evaluated and returned.
• This function has no name.
• It returns a function object which is assigned to the
identifier double.
• A lambda function does not contain a return statement.
• It contains a single expression as a body and not a block of
Exercise
• Write a program using lambda function to find
the product of two numbers.
product = lambda x, y: x * y

num1 = float(input("Enter the first number: "))


num2 = float(input("Enter the second number: "))

result = product(num1, num2)


print("The product is:", result)
Statement problem- Functions
The flight ticket rates for a round-trip (Mumbai->Dubai) were
as follows:
Rate per Adult: Rs. 37550.0
Rate per Child: 1/3rd of the rate per adult
Service Tax: 7% of the ticket amount (including all
passengers)
As it was a holiday season, the airline also offered 10%
discount on the final ticket cost (after inclusion of the
service tax).

Find and display the total ticket cost for a group which had
adults and children. Test the program with different input
values for number of adults and children.
Sample Input
Number of adults 5
Number of children 2

Number of adults 3
Number of children 1

Expected Output

Total Ticket Cost: 204910.35

Total Ticket Cost: 120535.5


Partial solution:
def calc_total_ticket_cost(no_of_adults, no_of_children):
total_ticket_cost=0
#Write your logic here

return total_ticket_cost

#Provide different values for no_of_adults,


no_of_children and test your program

total_ticket_cost=calc_total_ticket_cost(1,2)
print("Total Ticket Cost:",total_ticket_cost)
def calculate_total_ticket_cost(no_of_adults, no_of_children):
total_ticket_cost=0
rate_adult=37550.0
rate_child=37550.0 /3.0
ticket_cost=(no_of_adults*rate_adult)
+(no_of_children*rate_child)
tax=ticket_cost*.07
disc=(ticket_cost+ tax)*0.1
total_ticket_cost=(ticket_cost+ tax)-disc
return total_ticket_cost

#Provide different values for no_of_adults, no_of_children and test


your program
total_ticket_cost=calculate_total_ticket_cost(5,2)
print("Total Ticket Cost:",total_ticket_cost)
Quiz
• Consider the following snippet:
def test(n):
if n%7==0:
print('Hipp Hipp Hurrah')
else:
print('Alas')
What would be the output of test(27)?
a.) Hipp Hipp Hurrah
b.) Hipp
d) Alas
c.) Hurrah
d.) Alas
Quiz
• What is the output of the below program ?
x = 50
def func(x):
print('x is', x)
x=2
print('Changed local x to', x)
func(x)
print('x is now', x)

a) x is now 50
b) x is now 2
c) x is now 100 d) x is 50
d) x is 50 Changed local x to 2
x is now 50
Changed local x to 2
Quiz
• What is the output of below program?
def say(message, times = 1):
print(message * times)
say('Hello') a) Hello
say('World', 5) WorldWorldWorldWorldWorld

a) Hello
WorldWorldWorldWorldWorld
b) Hello
World 5
c) Hello
World,World,World,World,World
d) Hello
HelloHelloHelloHelloHello
Quiz
What is the output of below program?
def func(a, b=5, c=10):
print('a is', a, 'and b is', b, 'and c is', c)

func(3, 7)
a is 3 and b is 7 and c is 10
func(25, c = 24) a is 25 and b is 5 and c is 24
func(c = 50, a = 100) a is 100 and b is 5 and c is 50
Summary
• A function is a self-contained block.
• A function definition begins with def keyword.
• Arguments can be passed as positional or
keyword arguments.
• A variable must be created before it is used.
• Scope of the variables are based on where they
are defined – local or global.
• The return statement is used to return a value
from a function.
• Functions can return multiple values.
• Python also supports recursive functions.

You might also like