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
48
Practical lesson: functions
Textbook: p. 95
GoalIn the practical lesson, solves tasks with functions and procedures: finds the greatest number, prints even numbers, and calls a function inside another function.
New words
calling a function: writing its name with the values in brackets · funksiyani chaqirishnested call: the result of one call is used as an argument of another · ichma-ich chaqiruvprocedure: a function that prints but returns no value · protsedurabuilt-in name: names like max, len, print that should not be used for your own functions · o‘rnatilgan nom
Explanation
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.
Worked examples
The largest of three numbers: def katta(a, b): ⏎ if a > b: ⏎ return a ⏎ else: ⏎ return b ⏎ a = int(input()) ⏎ b = int(input()) ⏎ c = int(input()) ⏎ print(katta(katta(a, b), c)) For 14, 31, 22 it prints 31.
An even-numbers procedure: def juftlar(n): ⏎ for i in range(2, n + 1, 2): ⏎ print(i, end=" ") ⏎ juftlar(10) juftlar(10) prints 2 4 6 8 10 on the screen and returns no value.
Class activity
“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.
Practice
1
Write a program using a function kichik(a, b) to find the smallest of three numbers (4 for 9, 4, 6).
def kichik(a, b): ⏎ if a < b: ⏎ return a ⏎ else: ⏎ return b ⏎ print(kichik(kichik(9, 4), 6))
2
Write a function ortacha(a, b, c) that returns the mean of three numbers and print ortacha(4, 5, 9) (6.0).
def ortacha(a, b, c): ⏎ return (a + b + c) / 3 ⏎ print(ortacha(4, 5, 9))
3
What does juftlar(7) print on the screen?
2 4 6
4
Why is it better not to name our own function max?
max is a built-in function; our own name would hide it and cause confusion elsewhere.