Subprograms: functions and procedures
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.
| Part | Job |
|---|---|
| def name(parameters): | declares the function |
| return | gives the result back to the place of the call |
| name(values) | calls the function |
A school club wrote the same invitation to classmates each time. Then they made it one template where only the name changes. A function works the same way: written once and called many times.
Programmers, event organisers and office workers write a repeated job once as a template or function.
Pick a small calculation you repeat, such as changing minutes into hours, and write it on paper as a rule “f(x) = …”. Test it with two different inputs.
1def kvadrat(x): 2 return x * x 3print(kvadrat(7)) 4 5def salom(ism): 6 print("Salom,", ism + "!") 7salom("Lola")
49 Salom, Lola!
1def fakt(n): 2 if n == 0: 3 return 1 4 return n * fakt(n - 1) 5print(fakt(5)) 6 7def salom(): 8 print("Salom") 9x = salom() 10print(x)
120 Salom None
“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.