Practical lesson: functions
When working with functions first say the job of the function in one sentence: “returns the larger of two numbers”, “prints the even numbers up to n”. The first returns a value (return), so its result can be used in another expression: katta(katta(a, b), c) is the largest of three numbers. The second prints the result at once and returns no value, that is, it is a procedure. Choose a name by its meaning and avoid built-in names like max and len; this is why we named the function that finds the larger number katta. After writing a function test it by calling it with at least two different values. The declaration of a function must come before its call, otherwise a NameError appears.
In a class project several pupils each needed to check whether a score reached the pass mark (at least 50). Instead of everyone writing their own check, one pupil wrote a function once and the others called it. When a wrong sign was found, it was fixed in one place and everyone’s results were corrected.
Programmers, analysts and testers reuse ready functions to save time.
Choose a small job such as “returns the number of days in a given number of weeks”. Write the job in one sentence and add two input–output examples on paper.
1def katta(a, b): 2 if a > b: 3 return a 4 else: 5 return b 6a = int(input()) 7b = int(input()) 8c = int(input()) 9print(katta(katta(a, b), c))
31
1def juftlar(n): 2 for i in range(2, n + 1, 2): 3 print(i, end=" ") 4juftlar(10)
2 4 6 8 10
“Function library”: the group writes 3 small functions (the smaller, square, digit sum) and collects them in one file; another group calls and uses them in its own task.