Lessons 47–48 · 2 lessons · M. R. Fayziyeva, D. M. Sayfurov, N. S. Xaytullayeva. Informatics and Information Technologies, Grade 9. “Nashriyot uyi Tasvir”, Tashkent, 2020
47
Subprograms: functions and procedures
Textbook: pp. 91–94
GoalKnows the concepts of a subprogram, a function and a procedure, writes and calls a function with parameters using def and return, and explains recursion and its stopping condition.
New words
function: a named subprogram that takes parameters and may return a result · funksiyaparameter: a name in the brackets of def that receives the value passed when the function is called · parametrreturn: gives the result back to the place where the function was called · returnrecursion: a function that calls itself · rekursiya
Explanation
When the same job is repeated in several places in a program, it is handy to move it into a subprogram – a function: the code is written once and a mistake is fixed in one place. A function is declared with def name(parameters): and its body is written with an indent of 4 spaces; it works only when it is called: name(values). return is used to give the result back to the place of the call; without return the function returns nothing (None) – in the textbook such a subprogram is called a procedure. A function name should not be the same as built-in names such as max, len, print, otherwise they are “hidden”. If a function calls itself it is recursion: for example n! = n · (n − 1)!, 0! = 1. Recursion needs a stopping condition (if n == 0: return 1), otherwise the calls never stop and a RecursionError appears.
Worked examples
A function and a procedure: def kvadrat(x): ⏎ return x * x ⏎ print(kvadrat(7)) kvadrat(7) returns 49. def salom(ism): ⏎ print("Salom,", ism + "!") ⏎ salom("Lola") salom("Lola") prints Salom, Lola! on the screen and returns nothing.
Recursion: def fakt(n): ⏎ if n == 0: ⏎ return 1 ⏎ return n * fakt(n - 1) ⏎ print(fakt(5)) fakt(5) = 5 · fakt(4) = … = 5 · 4 · 3 · 2 · 1 · fakt(0), fakt(0) = 1, the result is 120. A subprogram that returns no value: def salom(): ⏎ print("Salom") ⏎ x = salom() ⏎ print(x) None goes into x.
Class activity
“A function is a machine”: the class plays a function as a “machine”: one pupil gives a parameter (for example 7), the “machine” pupil follows the rule (square) and returns the result (49); then the rules are changed.
Practice
1
What does the function f(x) = 2 * x + 1 return for f(4)?
9
2
Write a function yuza(a, b) that returns the product of two numbers and print yuza(6, 7).
def yuza(a, b): ⏎ return a * b ⏎ print(yuza(6, 7))
3
What is the recursive fakt(4) equal to?
24
4
Name two advantages of using functions.
The code is not repeated and a mistake needs to be fixed in only one place.