Calling Functions
To run a function, you call it: write its name followed by parentheses:
def say_hello():
print("Hello!")
print("Have a nice day!")
say_hello()This prints:
Hello!
Have a nice day!When Python gets to a call, it jumps into the function, runs its body from top to bottom and then continues with the line after the call. You can call a function as many times as you like:
def say_hello():
print("Hello!")
print("Start")
say_hello()
say_hello()
print("End")This prints:
Start
Hello!
Hello!
EndAt first, Python goes past the definition and only remembers the function. Then it prints Start, runs the body of the function twice and finally prints End. Notice that the calls aren't indented: they are not part of the body. The empty line after the function isn't required, but it makes the program easier to read.
Python reads a program from top to bottom, so a function must be defined before it is called. This program calls say_goodbye() on its first line, when Python doesn't know the function yet:
say_goodbye()
def say_goodbye():
print("Goodbye!")It ends with an error:
Traceback (most recent call last):
File "<exec>", line 1, in <module>
NameError: name 'say_goodbye' is not definedThat's why we define functions first, usually at the top of the program, and call them below their definitions.
Watch out for two more common mistakes:
- Forgetting the parentheses.
say_hellowithout them doesn't call the function, it only mentions it, so nothing happens, not even an error. Andprint(say_hello)doesn't call it either: it only prints something like<function say_hello at 0x...>. - A different name. The name in the call must be exactly the same as in the definition, including uppercase and lowercase letters, so
Say_hello()ends with the errorNameError: name 'Say_hello' is not defined. Did you mean: 'say_hello'?
Instructions
- 1
Below the function, call
first_functionthree times. - 2
Add a second line to the body of the function:
print("Functions are great!"). Run the program: each of the three calls now prints both lines. You changed the code in one place, and all three calls do something new. That's what functions are for.