Defining and Calling Functions
In this tutorial, we'll create functions with def and run them by calling their names.
To create a function, use def.
def say_hello():
print("Hello")
This defines the function. It does not run it yet.
To run the function, call it:
say_hello()
Output:
Hello
The Shape of a Function
A function definition has:
- The word
def - The function name
- Parentheses
- A colon
- An indented block of code
def function_name():
code_to_run
Indentation matters. The indented lines belong to the function.
Defining vs Calling
This code only defines the function:
def greet():
print("Hi")
Nothing appears on screen because the function was not called.
This code defines and calls it:
def greet():
print("Hi")
greet()
Calling More Than Once
Functions can be called many times:
def show_menu():
print("1. Start")
print("2. Settings")
print("3. Quit")
show_menu()
show_menu()
The same block runs each time.
Common Mistake
Forgetting parentheses means you refer to the function, but do not call it:
greet # does not run the function
greet() # runs the function
Define Before You Call
Python reads files from top to bottom. Define the function before calling it:
def say_goodbye():
print("Goodbye")
say_goodbye()
If you call say_goodbye() before the def line has run, Python will not know the function exists yet.
Practice
Create a function called show_profile() that prints a name, favourite language, and current goal. Call it twice.