Chapter 6: Functions and Modularity
Learn how to write functions in Python to make your code reusable, modular, and easy to maintain.
In this chapter, we�ll explore how to create functions, which allow you to organize your code into reusable, manageable units. Functions make code modular and help avoid repetition, making programs easier to maintain and expand.
What is a Function?
A function is a block of code that performs a specific task and can be reused throughout a program. Functions are defined using the def
keyword and can take parameters to handle different data each time they�re called.
Defining a Basic Function
To define a function, use the def
keyword, followed by the function name and parentheses. Here�s an example:
def greet():
print("Hello, world!")
In this example, calling greet()
will execute the code inside the function, printing "Hello, world!" to the console.
Function Parameters
Parameters allow you to pass data into functions, making them more flexible and reusable. Here�s an example with a parameter:
def greet(name):
print(f"Hello, {name}!")
Calling greet("Alice")
would output "Hello, Alice!" to the console.
Return Values
Functions can return values using the return
keyword, allowing you to store or further process their output:
def add(a, b):
return a + b
In this example, add(3, 5)
would return 8
, which you can store in a variable or use in other calculations.
Default Parameters
You can assign default values to parameters, making them optional. If a parameter with a default isn�t provided, the function uses the default value:
def greet(name="World"):
print(f"Hello, {name}!")
Calling greet()
would output "Hello, World!", while greet("Alice")
would output "Hello, Alice!".
Scope of Variables
Variables declared inside a function are local to that function and aren�t accessible outside of it. This keeps functions self-contained and helps avoid unintended side effects:
def my_function():
x = 10 # x is local to my_function
print(x)
my_function()
print(x) # This would raise an error, as x is not defined outside my_function
In this example, the variable x
is only accessible within my_function
.
Lambda Functions
Python also supports anonymous functions, called lambda functions, which are defined without a name using the lambda
keyword. They are useful for short, simple functions:
square = lambda x: x ** 2
print(square(5)) # Outputs 25
In this example, square
is a lambda function that squares its input.
Summary and Next Steps
In this chapter, we covered the basics of functions, including parameters, return values, and scope. You also learned about lambda functions, a shorthand for defining simple functions. In the next chapter, we�ll explore how to handle user input and interact with users through programs.