How to organize reusable code using functions
Functions are reusable blocks of code that perform specific tasks. They help keep your programs organized, readable, and efficient.
Use the def keyword to define a function:
def greet():
print("Hello from a function!")
Once defined, you call a function by using its name followed by parentheses:
greet()
Parameters allow you to pass information into a function:
def greet(name):
print(f"Hello, {name}!")
greet("Alice")
greet("Bob")
def add(a, b):
return a + b
result = add(3, 5)
print(result) # 8
Functions can return values using the return statement:
def square(x):
return x * x
print(square(4)) # 16
You can assign default values to parameters:
def greet(name="friend"):
print(f"Hello, {name}!")
greet() # Hello, friend!
greet("Charlie") # Hello, Charlie!
Arguments can be passed by name:
def introduce(name, age):
print(f"{name} is {age} years old.")
introduce(age=30, name="Alice")
Use *args for multiple positional arguments:
def total(*numbers):
return sum(numbers)
print(total(1, 2, 3, 4)) # 10
Use **kwargs for multiple keyword arguments:
def show_info(**info):
print(info)
show_info(name="Alice", age=30)
Now that you understand functions, you’re ready to learn how Python organizes code into modules and packages in Lesson 9: Modules and Packages.
← Back to Lesson Index