Line At A Time
Lesson 23: Functions
Functions Write your own function and call it twice.
1def wave():
2 print("Hello!")
3 print("How are you?")
4
5wave()
6wave()
Terminal
$ python3 main.py
Hello!
How are you?
Hello!
How are you?
Every line, explained
def wave():
def defines a function: your own named block of code. The name is followed by round brackets and a colon, and the body is indented. Defining a function does nothing on its own: it waits until somebody calls it. In Python you must define a function before the line that calls it.
print("Hello!")
print(...) shows whatever is inside its round brackets in the terminal, then moves to a new line. It is written all in lowercase, and it needs both brackets. Indented, so it is part of the wave function's body.
print("How are you?")
print(...) shows whatever is inside its round brackets in the terminal, then moves to a new line. It is written all in lowercase, and it needs both brackets. Also part of the body: the function prints two lines every time it runs.
wave()
Writing the function's name with round brackets calls it: Python jumps up into wave, runs its body, then comes back here. (The blank line above is just for readability; Python ignores it.)
wave()
Calling it again runs the body again. Write once, use as many times as you like. That is the whole point of functions!