3.functions
3.functions
1 import random
2 for i in range(5):
3 print(random.randint(1, 6))
4
5 2
6 4
2
1
6
1 import sys
2
3 while True:
4 print('Type exit to exit.')
5 response = input()
6 if response == 'exit': Type exit to exit.
7 sys.exit() hello
You typed hello.
8 print('You typed ' + response + '.')
Type exit to exit.
exit
>>>
2. Parameters
• Allows a function to accept data from its caller
• Allows programmers to reuse code for different values
CSCI2040 INTRODUCTION TO PYTHON 15
1 def foo(n):
2 print("{}".format(n)) n = 13
3
n=3
4
5
n = 10
6 x = 10
7
8 foo(3)
9 foo(x)
10 foo(x + 3)
11 3
10
12
13
13
x = 10 def bar(n):
bar(x) print("n is {}" .format(n))
print("x is {}" .format(x)) n = n + 1
Output
n is 10
x is 10
Output
[1, 2, 3, 4]
[1, 2, 3, 4, [5, 6, 7]]
1. For simple data such as integer and floating point numbers, pass by
value
⚫ parameter_list
Zero or more parameters separated by commas in the form
param1, param2, …, paramN
Example:
An improved version of printBar()
CSCI2040 INTRODUCTION TO PYTHON 21
1 def foo(x, y):
2 print("{} {}" .format(x, y))
3
4 x = 3
5 y = 2
6
7 foo(x, y)
8
9 foo(y, x)
10
Keyword arguments
Default arguments
Cube of 3 is 27
Cube of 8 is 512
⚫ return expression
return is a keyword, it returns the value of expression to
the caller.
expression is evaluated first before return is executed.
def cube(x) :
return x * x * x
x = 1 + cube(2) * cube(3);
x = 1 + 8 * cube(3);
x = 1 + 8 * 27;
x = 1 + 216;
x = 217;
if (m == 4 or m == 6 or m == 9 or m == 11):
return 30;
# if y is a leap year
if (y % 4 == 0 and y % 400 == 0):
return 29
Only one of the "return"
return 28 statements will be executed.
CSCI2040 INTRODUCTION TO PYTHON 30
Example (with only one return)
def daysPerMonth(m, y):
" Returns number of days in a particular month "
if (m == 1 or m == 3 or m == 5 or
m == 7 or m == 8 or m == 10 or m == 12):
days = 31
elif (m == 4 or m == 6 or m == 9 or m == 11):
days = 30;
else:
# if y is a leap year
if (y % 4 == 0 and y % 400 == 0):
days = 29
A function is easier to debug if there
else:
is only one return statement
days = 28
return days
because we know exactly where an
execution leaves the function.
CSCI2040 INTRODUCTION TO PYTHON 31
The return keyword
• If there is no data to be returned, write
return
Nested Function
def ListofSquares( a ):
return [x*x for x in a]
>>> ListofSquares([1,2,3])
[1, 4, 9]
def f( n ):
if( n==1):
result = 1
else:
result = n * f(n-1)
return result
>>> print (f(3))
6