Functions: code written once, used many times
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.
1def greet(name): 2 print("Hello", name) 3 4greet("Nour") 5greet("Sami")
Hello Nour Hello Sami
1def show_line(): 2 print("----------") 3 4print("Menu") 5show_line() 6print("Thank you") 7show_line()
Menu ---------- Thank you ----------
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?
1def greet(name): 2 print("Hello", name) 3 4greet("Nour") 5greet("Sami")