Chapter 6
Chapter 6
Functions
CPIT 110 (Problem-Solving and Programming)
Modified by Ahmad Khoj
Sum from 1 to 10 is 55
Sum from 20 to 37 is 513
Sum from 35 to 49 is 630
6.1 Program 1 2
Sum Many Numbers
Implementation
SumManyNumbers.py
1 # Sum from 1 to 10
2 sum = 0
3 for i in range(1, 11):
4 sum += i
5 print("Sum from 1 to 10 is", sum)
6
7 # Sum from 20 to 37
8 sum = 0
9 for i in range(20, 38):
10 sum += i
11 print("Sum from 20 to 37 is", sum)
12
13 # Sum from 35 to 49
14 sum = 0
15 for i in range(35, 50):
16 sum += i
17 print("Sum from 35 to 49 is", sum)
6.1 Program 1 3
Sum Many Numbers
Implementation (Improved)
The first implementation can be simplified by using functions, as follows:
SumManyNumbersUsingFucntions.py
1 def sum(x, y):
2 result = 0
3 for i in range(x , y + 1):
4 result += i
5 print("Sum from ", x, "to ", y, "is ", result)
6
7 sum(1, 10)
8 sum(20, 37)
9 sum(35, 49)
Sum from 1 to 10 is 55
Sum from 20 to 37 is 513
Sum from 35 to 49 is 630
6.1 Program 1 4
Defining a Function
• What is a function?
◦ A function is a collection of statements grouped together to perform an operation.
• Guess what?
◦ You have already used many predefined functions!
◦ Examples:
print("message") eval("numericString") random.randint(a, b)
• Function’s definition defines the function, but it does not cause the function to
execute.
◦ A function is being executed when it is called or invoked.
6.2 5
Anatomy of a Function
Defining a Function
• This function, named max, has two parameters, num1 and
num2. It returns the largest number from these parameters.
Return Value
6.2 6
Calling a Function
That Returns a Value
There are two ways to call a function, depending on whether or
not it returns a value:
1. If the function returns a value, a call to that function is usually
treated as a value.
Example #1:
larger = max(3, 4)
6.3 7
Calling a Function
That Does Not Return a Value
2. If a function does not return a value, the call to the function
must be a statement.
Example:
print("This is a parameter!")
6.3 8
Program Control
• When a program calls a function, program control is
transferred to the called function.
• A called function returns control to the caller when:
◦ Its return statement is executed.
◦ Or the function is finished.
Program Control
Main A
Statement 2 Statement
1
Statement B()
A() Statement
4
Statement Statement
Statement
Statement 5 Execution Order B
Statement
Statement … Statement(s) 3
6.3 9
Testing max Function
Program 2
Write a program that will call a function, max, to determine the maximum of two
numbers. Function max should return the maximum value. Suppose the two
numbers are 2 and 5.
LISTING 6.1 TestMax.py
1 # Return the max between two numbers
2 def max(num1, num2):
3 if num1 > num2:
4 result = num1
5 else:
6 result = num2
7
8 return result
9
10 i = 5
11 j = 2
12 k = max(i, j) # Call the max function
13 print("The maximum between", i, "and", j, "is", k)
6.3 Program 2 10
Functions without Return Values
• The previous example (max function) was a value-returning
function.
Meaning, it returned a value (the max) to the caller.
• Some functions do not return anything at all.
A function does not have to return a value.
• This kind of function is commonly known as a void function in
programming terminology.
• The following program (Program 3) defines a function named
printGrade and invokes (calls) it to print the grade based on a
given score.
6.4 11
Testing Void Function
LISTING 6.2 PrintGradeFunction.py
Program 3
1 # Print grade for the score
2 def printGrade(score):
3 if score >= 90.0:
4 print('A')
5 elif score >= 80.0:
6 print('B')
7 elif score >= 70.0:
8 print('C')
9 elif score >= 60.0:
10 print('D')
11 else:
12 print('F')
13
14 score = eval(input("Enter a score: "))
15 print("The grade is ", end = "")
16 printGrade(score) # Call the printGrade function
6.4 Program 4 13
Void Values vs Return Values
1 # Print grade for the score 1 # Return the grade for the score
2 def printGrade(score): 2 def getGrade(score):
3 if score >= 90.0: 3 if score >= 90.0:
4 print('A') 4 return 'A'
5 elif score >= 80.0: 5 elif score >= 80.0:
6 print('B') 6 return 'B'
7 elif score >= 70.0: 7 elif score >= 70.0:
8 print('C') 8 return 'C'
9 elif score >= 60.0: 9 elif score >= 60.0:
10 print('D') 10 return 'D'
11 else: 11 else:
12 print('F') 12 return 'F'
13 13
14 score = eval(input("Enter a score: ")) 14 score = eval(input("Enter a score: "))
15 print("The grade is ", end = "") 15 print("The grade is", getGrade(score))
16 printGrade(score) 16
17 ''' or we can save function in variable
18 result = getGrade(score)
19 print("The grade is", result )
The printGrade function does not return 20 '''
any value.
The getGrade function returns value.
6.4 14
None Value
• If you run the following program:
1 def sum(number1, number2):
2 total = number1 + number2
3
4 print(sum(1, 2))
None
• You will see the output is None, because the sum function does
not have a return statement.
• By default, it returns None.
6.4 15
Check Point
What are the benefits of using a function?
6.4 16
Check Point
Can you simplify the max function by using a conditional
expression?
Solution:
1 def max(num1, num2):
2 return num1 if num1 > num2 else num2
6.4 17
Check Point
Identify and correct the errors in the following program:
1 def function1(n, m): Extra unnecessary parameter (m)
2 function2(3.4)
Fixed value instead of using the parameter (n)
3
4 def function2(n): Incorrect indentation
5 if n > 0: (Syntax Error)
6 return 1
7 elif n == 0:
8 return 0
9 elif n < 0:
10 return -1
11
12 function1(2, 3) The function doesn’t return a value or make actions
6.4 18
Check Point
Identify and correct the errors in the following program:
Solution: the following code is the corrected code:
1 def function1(n):
2 print(function2(n))
3
4 def function2(n):
5 if n > 0:
6 return 1
7 elif n == 0:
8 return 0
9 elif n < 0:
10 return -1
11
12 function1(2)
6.4 19
Check Point
Show the output of the following code:
1 def main():
2 print(min(5, 6))
3
4 def min(n1, n2):
5 if n1 < n2:
6 smallest = n1
7 else:
8 smallest = n2
9
10 main() # Call the main function
None
6.4 20
Check Point
Show the output of the following code:
Solution: the following code is the corrected code.
1 def main():
2 print(min(5, 6))
3
4 def min(n1, n2):
5 if n1 < n2:
6 return n1
7 else:
8 return n2
9
10 main() # Call the main function
6.4 21
Check Point
Show the output of the following code:
1 def main():
2 print( min( min(5, 6) , min(51, 3) ) )
3
4 def min(n1, n2):
5 if n1 < n2:
6 return n1
7 else:
8 return n2
9
10 main() # Call the main function
11
6.4 22
Check Point
Show the output of the following code:
1 def printHi(name):
2 message = "Hi " + name #should print the value
3
4 def printHello(name):
5 message = "Hello " + name
6 print(message)
7
8 def getHello(name):
9 return "Hello " + name
10
11 printHi("Ahmad")
12 printHello("Zaki")
13 getHello("Rashad")#should call the function in the print
14 print("#", getHello("Khoj"), "#")
Hello Zaki
# Hello Khoj #
6.4 23
Check Point
Show the output of the following code:
1 def A():
2 return 1
3 print("A")
4 return 2
5 def B():
6 print("B")
7 if not True:
8 return 10
9 else:
10 return 3
11 return 5
12 r = A()
13 r += B()
14 print(r)
B
4
6.4 24