Defining functions
Create your own reusable functions
In Python, functions let you group code to perform a specific task, making your programs organized and easy to reuse.
Your first function
Imagine you have a few lines of code that you use many times. Instead of typing it out every time, you can put it in a function. This makes your code cleaner and easier to manage.
def greet():
print("Hello, Pythonista!")
greet() # This calls the functionFunction syntax
Let's break down how to declare a function in Python. It's quite simple!
- You start with the
defkeyword, which means "define function." - Next comes the function name, like
greetin our example. - Parentheses
()always follow the name. These can hold inputs, called parameters. - A colon
:ends thedefline. - The function's code block is indented. This indentation tells Python what code belongs to the function.
def function_name(parameter1, parameter2):
# This is the function's body
# It tells the function what to do
print("Inside the function")Naming functions
Good function names are important. They make your code understandable.
- Use lowercase letters.
- Separate words with underscores (
_). This is calledsnake_case. - Choose names that describe what the function does, like
calculate_totalorsend_email.
Calling functions
Defining a function doesn't execute its code. You need to "call" or "invoke" it to make it run.
def say_hello():
print("Hello there!")
# Call the function by its name followed by parentheses
say_hello()Functions with logic
Functions aren't just for single print statements. They can contain any Python code, including if statements, loops, or even calls to other functions.
def check_age(age):
if age >= 18:
print("You are an adult.")
else:
print("You are a minor.")
check_age(20)
check_age(16)Variable scope: Local vs Global
Where you define a variable affects where it can be used. This concept is called scope.
Local variables
Variables created inside a function are "local." They only exist and can be accessed within that function. Once the function finishes, they disappear.
def my_function():
message = "This is a local variable."
print(message)
my_function()
# print(message) # This would cause an error because message is localGlobal variables
Variables defined outside any function are "global." They can be accessed from any part of the program, including inside functions.
global_name = "Alice"
def greet_global():
print(f"Hello, {global_name}!")
greet_global()
print(global_name)Modifying global variables
If you want to change a global variable from inside a function, you need to use the global keyword. Otherwise, Python will create a new local variable with the same name.
count = 0 # Global variable
def increment_count():
global count # Declare intent to modify the global variable
count += 1
print(f"Before: {count}")
increment_count()
print(f"After: {count}")Best practice: Use parameters and returns
Instead of relying on global variables, it's usually better to pass data into functions as parameters and get results back using return statements.
def add_numbers(num1, num2):
result = num1 + num2
return result # Send the result back
sum_value = add_numbers(5, 3)
print(f"The sum is: {sum_value}")Common mistakes
- Forgetting the colon
:at the end of thedefline. - Incorrect indentation for the function body.
- Not calling the function after defining it, which means it will never run.
- Trying to access a local variable outside its function scope.
- Forgetting
globalwhen intending to modify a global variable.
Practice
Try these exercises to lock in what you just learned.
12 print("hi")3greet()
What's next?
You've learned the basics of functions! Next, you can explore functions that take different types of arguments and how to make your functions even more flexible.