Defining and Calling Functions
Now that you understand what functions are, let's create one. In Python, you define a function using the def keyword, give it a name, and write the code it should execute. Then you call it whenever you need that code to run.
Defining a Function
The basic syntax looks like this:
def greet():
print("Hello!")
print("Welcome to Python!")
Let's break this down:
deftells Python you're defining a functiongreetis the function's name (you choose this)()holds parameters (empty for now — we'll add these later):marks the start of the function body- The indented lines are the function body — the code that runs when you call it
Important: Defining a function doesn't run its code. You're just teaching Python what greet means. The code inside won't execute until you call the function.
Calling a Function
To execute the function's code, call it by name with parentheses:
def greet():
print("Hello!")
print("Welcome to Python!")
# Now call it
greet()
When Python sees greet(), it jumps to the function definition, runs the indented code, then returns to where it left off.
Calling Multiple Times
The real power shows when you call a function repeatedly:
def greet():
print("Hello!")
print("Welcome to Python!")
greet() # First call
greet() # Second call
greet() # Third call
This prints the greeting three times. Without functions, you'd copy those two print statements three times — and if you wanted to change the message, you'd edit it in three places.
Definition Must Come First
Python reads your code from top to bottom. You must define a function before calling it:
# This works
def say_hi():
print("Hi!")
say_hi()
# This fails - function not defined yet
say_goodbye() # Error!
def say_goodbye():
print("Goodbye!")
A Complete Example
def show_menu():
print("=== Main Menu ===")
print("1. Start Game")
print("2. Load Game")
print("3. Exit")
print("=================")
# Use the function throughout your program
show_menu()
# ... user makes choice ...
# ... later in the program ...
show_menu() # Show menu again
You've now created reusable code. In the next lessons, you'll learn to make functions more flexible by passing information into them.