Python Programming for Applied Projects
Functions
Packaging Your Code
So far, you've written code that runs from top to bottom. If you needed to repeat a task, you probably used a loop. But what if you need to perform the same complex task at many different places in your program? Copying and pasting code is messy and hard to maintain.
Functions solve this problem. They are reusable blocks of code that perform a specific action. You define a function once and can then call it whenever you need it, as many times as you want. This makes your programs more organized, readable, and efficient.
Think of functions as named recipes for your program. You write the recipe once, then you can 'cook' it just by calling its name.
To define a function in Python, you use the def keyword, followed by the function's name, a set of parentheses (), and a colon :. The code that belongs to the function is indented on the following lines, just like with loops and if statements.
def say_hello():
# This block of code is inside the function
print("Hello there!")
print("Welcome to the world of functions.")
# To run the code inside the function, you must call it:
say_hello()
Defining the function doesn't run its code. It just tells Python, "Here is a set of instructions called say_hello." You have to explicitly call the function by writing its name followed by parentheses to execute the code inside it.
Passing in Data
Most functions need some input to work with. Our say_hello function is a bit limited because it does the exact same thing every time. We can make it more flexible by allowing it to accept information when it's called.
This is done using parameters and arguments.
Parameter
noun
A variable listed inside the parentheses in the function definition. It acts as a placeholder for the data the function expects to receive.
Argument
noun
The actual value that is sent to the function when it is called. This value is assigned to the corresponding parameter.
Let's modify our greeting function to accept a name. Here, name is the parameter.
def greet(name):
# 'name' is a parameter
print(f"Hello, {name}!")
# "Alice" and "Bob" are arguments
greet("Alice")
greet("Bob")
When greet("Alice") is called, the value "Alice" is passed into the function and assigned to the name parameter. The function can then use this variable internally.
You can also define functions that accept multiple parameters. Simply separate them with commas.
def calculate_area(length, width):
area = length * width
print(f"The area is: {area}")
# Call it with two arguments
calculate_area(10, 5)
Getting Values Back
Printing a result to the console is useful, but often you need the function's result for use in another part of your program. For this, we use the return statement.
When a function encounters a return statement, it immediately stops executing and sends the specified value back to where the function was called.
def add(num1, num2):
total = num1 + num2
return total
# The value returned by add() is stored in the 'sum_result' variable
sum_result = add(8, 4)
print(f"The result is: {sum_result}")
# You can also use the returned value directly
print(f"Two plus three is: {add(2, 3)}")
A function that doesn't have a return statement implicitly returns a special value called None.
The Scope of Variables
An important concept with functions is variable scope. Scope determines where in your program a variable can be accessed.
Variables created inside a function are called local variables. They only exist inside that function. Once the function finishes running, the local variables are destroyed and cannot be accessed from outside.
Variables defined outside of any function are called global variables. They can be accessed from anywhere in your script, including from inside any function.
# 'message' is a global variable
message = "I am a global variable"
def some_function():
# 'local_var' is a local variable
local_var = "I only exist inside this function"
print(local_var) # This works
print(message) # This also works, we can access global variables
some_function()
# Try to access the local variable from outside
# This will cause an error!
# print(local_var)
Using local variables is preferred. It prevents functions from accidentally modifying variables used in other parts of your program, which can lead to hard-to-find bugs.
Which keyword is used to start a function definition in Python?
In the following code, what is 'Alice' an example of?
def greet(name):
print(f'Hello, {name}!')
greet('Alice')
You now have a powerful tool for organizing your code. Functions are a core concept in almost every programming language, and mastering them is a huge step forward.