☰ خطة العام · تكنولوجيا المعلومات والاتصالات (بالإنجليزية)

Functions

الأسبوع 8 · الدرس ٤ «الدوال ذات المعاملات في لغة Python»: الدالة والمعاملات ومساحة الدائرة وإرجاع القيمة · 3 دروس
3

Giving an answer back with return

ICT Prep 3 Term 1, Unit 1, Lesson 4: pp. 44–52
GoalReturn a value with return, tell return from print, and know that local variables live inside the function.
New words
return · sends a value back to the place that called the functionNone · the value of a function that returns nothinglocal variable · a variable that exists only inside its functionNameError · shown when a name is not known
Explanation

print shows a value on the screen. return hands a value back, so the program can store it or use it again. Study circle_area. It has a parameter radius, a local variable pi and the line return pi * radius * radius. The call circle_area(5) gives 78.5, which result stores. The number 3.14 is only an approximation of pi, so the answers are approximate too. A function that only prints gives back None, so the line result = add_print(2, 3) stores None. A function with return gives a real value: result * 2 works. The names pi and radius live only inside the function. Outside it, print(pi) causes a NameError.

Python
1def circle_area(radius):
2    pi = 3.14
3    return pi * radius * radius
4
5result = circle_area(5)
6print(result)
7print(circle_area(10))
Output
78.5
314.0
Worked examples
Python
1def add_print(a, b):
2    print(a + b)
3
4def add_return(a, b):
5    return a + b
6
7result = add_print(2, 3)
8print(result)
9result = add_return(2, 3)
10print(result * 2)
Output
5
None
10
Compare two functions. add_print only prints, so the result variable holds None. add_return hands the value back, so result is 5 and result * 2 shows 10.
Python
1def triangle_area(base, height):
2    return 0.5 * base * height
3
4print(triangle_area(6, 4))
Output
12.0
A new formula with return: the area of a triangle is half of base times height. With base 6 and height 4 the function gives 12.0, because 0.5 makes the result a decimal.
Python
1def circle_area(radius):
2    pi = 3.14
3    return pi * radius * radius
4
5print(pi)
Output
NameError: pi exists only inside the function
The names inside a function are local. pi was created inside circle_area, so outside the function Python does not know it and stops with a NameError.
Class activity

Write a function celsius_to_f(c) that returns c * 9 / 5 + 32. Work out by hand the result for 25 and for 100. Then write the line that stores the result for 25 in a variable called warm.

Practice
1
What does circle_area(10) give with pi = 3.14?
Python
1def circle_area(radius):
2    pi = 3.14
3    return pi * radius * radius
4
5result = circle_area(5)
6print(result)
7print(circle_area(10))
2
What is the difference between print and return?
3
What does result hold after result = add_print(2, 3)?
4
Why is pi = 3.14 only an approximation?