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

Functions

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

Functions: code written once, used many times

ICT Prep 3 Term 1, Unit 1, Lesson 4: pp. 44–52
GoalExplain why we write functions, define a simple function with def and call it more than once.
New words
function · a named block of code that can be used again and againdef · the Python word that starts a function definitioncall · a line that runs a functionbody · the indented lines inside a function
Explanation

Think of a vending machine: you press a button, the machine does a job and gives something back. You do not rebuild the machine each time. A function works the same way: code written once, with a name, and used many times. Without functions you would copy the same lines again and again; with a function you change one place and every use is updated. To define a function we write def, the name, brackets and a colon, then the indented body. Defining it does nothing yet. The function runs only when we call it, by writing its name with brackets. In greet(name), the word name in the brackets is a placeholder for the value we will send in; the next lesson gives it its proper name.

Worked examples
Python
1def greet(name):
2    print("Hello", name)
3
4greet("Nour")
5greet("Sami")
Output
Hello Nour
Hello Sami
Nour defines greet once and calls it twice with two names. The definition itself shows nothing. Each call shows one greeting.
Python
1def show_line():
2    print("----------")
3
4print("Menu")
5show_line()
6print("Thank you")
7show_line()
Output
Menu
----------
Thank you
----------
A menu uses the same decorative line twice. The function show_line is written once and called twice. If Omar wants a longer line he changes one place.
Class activity

Write on paper a function called welcome that shows Welcome to the club. Then write the three lines that call it three times. What does the screen show? What would happen if you only wrote the definition?

Practice
1
What is a function?
2
How many greetings does the picture program show?
Python
1def greet(name):
2    print("Hello", name)
3
4greet("Nour")
5greet("Sami")
3
Does writing def greet(name): run the function?
4
Give one reason to use a function instead of copying lines.