4: Functions
4.1 What Are Functions and Why Use Them?
A function is a block of code that performs a specific task. Think of a function as a recipe: it has a name, a list of ingredients (inputs), and a result (output). By defining a function, you can reuse that block of code as many times as you need without having to write it again.
Advantages of Using Functions:
- Code reuse: Avoid repeating the same code over and over again. If you need to perform the same task in different parts of your program, you simply "call" the function.
- Organization: Break your code into smaller logical blocks, making it easier to read, understand, and debug.
- Maintainability: If you need to change the logic of a task, you only have to modify the function in one place.
4.2 Defining and Calling Functions
To define a function, we use the keyword def
, followed by the function name and parentheses ()
. The function’s code block must be indented.
Example of a Simple Function
def greet():
print("Hello, welcome to the Python course!")
# Call the function
greet()
Functions with Parameters
Functions can receive information through parameters, which act like variables defined when creating the function. When you call the function, you pass arguments, which are the actual values assigned to those parameters.
def greet_person(name):
print(f"Hello, {name}! Nice to meet you.")
# Call the function with an argument
greet_person("Anna")
# Call the function with another argument
greet_person("Peter")
You can have multiple parameters in a function:
def add(a, b):
print(f"The sum of {a} and {b} is {a + b}.")
add(5, 3)
4.3 Returning Values with return
Often, you’ll want a function to give back a result to use in other parts of your program. For that, we use the keyword return
.
def multiply(a, b):
result = a * b
return result
# Call the function and store its result in a variable
product = multiply(4, 6)
print(product) # Output: 24
Once a return
statement is executed, the function ends. You can use return
without a value to simply exit the function.
4.4 Global and Local Variables
Variables you create inside a function have a local scope; they only exist within that function. Variables you create outside any function have a global scope and can be used anywhere in the program.
# Global variable
course_name = "Python Course"
def show_course():
# Local variable
lesson = "Functions"
print(f"You are in the {course_name}, lesson: {lesson}")
show_course()
# print(lesson) # This would cause an error, 'lesson' is not defined globally
It’s a good practice to avoid modifying global variables from inside a function. If you need to, you can use the keyword global
, but use it carefully to avoid confusion in your code.
counter = 0
def increment_counter():
global counter
counter += 1
increment_counter()
print(counter) # Output: 1
This module has taught you how to create and use functions, a crucial skill for writing clean and modular code. In the next module, we’ll explore Object-Oriented Programming (OOP), a paradigm that takes code organization and reuse to the next level.