Lesson 6: Python Functions
As your Python programs grow larger, you will quickly realize that writing the exact same logic in multiple places is a nightmare. If you need to fix a bug or change how something works, you have to hunt down every single instance and update it.
This is where functions come in. A function is essentially a mini-program within your main program. It allows you to package a block of code, give it a name, and reuse it as many times as you want without rewriting it.
Functions help you achieve one of the most important rules in programming: DRY (Don’t Repeat Yourself).
1. Defining a Function
To create a function in Python, you use the def keyword (short for define). After that, you give your function a descriptive name, followed by parentheses () and a colon :.
Just like with if statements and loops, the code that belongs inside the function must be indented.
Python
# Defining the function
def greet_user():
print("Hello there!")
print("Welcome to our application.")
# Calling (running) the function
greet_user()
greet_user()
Notice that defining the function does not actually run the code inside it. It just teaches Python what greet_user means. To execute the code, you have to “call” the function by typing its name followed by parentheses.
2. Passing Information In (Parameters and Arguments)
A function that does the exact same thing every time is useful, but a function that can adapt based on input is much more powerful. You can pass variables into your functions to make them dynamic.
The variables listed in the definition are called parameters. The actual data you pass in when you call the function are called arguments.
Python
# 'name' is the parameter
def greet_by_name(name):
print("Hello " + name + "!")
# 'Alice' and 'Bob' are the arguments
greet_by_name("Alice")
greet_by_name("Bob")
You can pass multiple parameters by separating them with commas:
Python
def calculate_total(price, tax_rate):
total = price + (price * tax_rate)
print("The final total is:", total)
calculate_total(100, 0.05)
3. Getting Information Out (The return Statement)
In the examples above, the functions simply printed information to the screen. But in real-world programming, you usually want a function to perform a calculation and hand the result back to you so you can use it later in your code.
You do this using the return keyword. As soon as a function hits a return statement, it stops running and passes the value back.
Python
def multiply_numbers(a, b):
result = a * b
return result
# The function hands back the value, and we store it in a variable
math_answer = multiply_numbers(5, 4)
print("The answer is:", math_answer)
4. Default Parameters (The Backup Plan)
Sometimes you want a parameter to have a default value just in case the user forgets to provide one. You can set this up directly in the function definition.
Python
def order_coffee(size="Medium"):
print("Brewing a " + size + " coffee.")
# Uses the argument provided
order_coffee("Large")
# Uses the default value because nothing was provided
order_coffee()
Ready to continue?
Move on to the next lesson to keep learning.
Continue: Lesson 7: Python Lists and Tuples