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

Chapter 6

Chapter 6 of the document focuses on functions in Python, explaining their definition, implementation, and usage. It includes examples of functions that return values and void functions, along with practical exercises for summing numbers and determining maximum values. The chapter also discusses the benefits of using functions, such as code reuse and reduced complexity.

Uploaded by

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

Chapter 6

Chapter 6 of the document focuses on functions in Python, explaining their definition, implementation, and usage. It includes examples of functions that return values and void functions, along with practical exercises for summing numbers and determining maximum values. The chapter also discusses the benefits of using functions, such as code reuse and reduced complexity.

Uploaded by

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

Chapter 6

Functions
CPIT 110 (Problem-Solving and Programming)
Modified by Ahmad Khoj

Introduction to Programming Using Python, By: Y. Daniel Liang


Version 2.0
Sum Many Numbers
Program 1
Write a program that will sum three sets of numbers and then
display the sum of each:
◦ Sum of integers from 1 to 10.
◦ Sum of integers from 20 to 37.
◦ Sum of integers from 35 to 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 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)

• These functions are defined in the Python library.


• A function definition consists of:
◦ Function name
◦ Parameters
◦ Body
• Syntax:
def functionName(list of parameters)
# Function body

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

Function Name Formal Parameters Define a function Invoke a function

1 def max(num1, num2): Function Header


2
3 if num1 > num2: z = max(x, y)
4 result = num1
5 else:
Function Body Actual Parameters
6 result = num2
7 (Arguments)
8 return result

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)

 Here, we "call" the function, max(3, 4).


 The maximum number, which is 4, will get returned.
 We save that value (4) into the variable larger.
 Example #2:
print(max(3, 4))

 Here, we directly print the result, which is 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!")

 Here, we "call" the print function.


 We send over the string, "This is a parameter!".
 That function receives the string and prints to output.

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)

The larger number of 5 and 2 is 5

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

Enter a score: 85 <Enter>


The grade is B
The printGrade function does not return any value.
6.4 Program 3 12
Testing getGrade Function
Program 4
LISTING 6.3 ReturnGradeFunction.py
1 # Return the grade for the score
2 def getGrade(score):
3 if score >= 90.0:
4 return 'A'
5 elif score >= 80.0:
6 return 'B'
7 elif score >= 70.0:
8 return 'C'
9 elif score >= 60.0:
10 return 'D'
11 else:
12 return 'F'
13
14 score = eval(input("Enter a score: "))
15 print("The grade is", getGrade(score))

Enter a score: 85 <Enter>


The grade is B

The getGrade function returns value.

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?

 Answer: At least three benefits:


1) Reuse code.
2) Reduce complexity.
3) Easy to maintain.

6.4 16
Check Point
Can you simplify the max function by using a conditional
expression?

1 def max(num1, num2):


2 if num1 > num2:
3 return num1
4 else:
5 return num2

 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

 Solution: the following slide has the corrected code.

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

 Solution: the following slide has the corrected code.

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

You might also like