Section Overview
Functions are blocks of code that perform a specific task and can be reused throughout your program. This section introduces how to define, call, and use functions in Python.
By the end of this section, you should be able to:
- Define your own functions using
def
- Pass inputs to functions with parameters
- Return values from functions
- Understand the benefits of reusable, organized code
Lesson 1: Defining and Calling Functions
A function is defined using the def
keyword followed by the function name and parentheses.
Example:
def greet():
print("Hello, world!")
To run the function, call it by its name with parentheses:
greet()
This prints:
Hello, world!
Lesson 2: Parameters and Arguments
Functions can accept inputs, called parameters, to work with.
Example:
def greet(name):
print("Hello, " + name + "!")
Call it with an argument:
greet("Alice")
Output:
Hello, Alice!
Lesson 3: Returning Values
Functions can send results back using the return
statement.
Example:
def add(a, b):
return a + b
Use the function and save the result:
result = add(3, 5)
print(result) # Outputs: 8
Lesson 4: Why Use Functions?
- Avoid repeating code (DRY principle: Don’t Repeat Yourself)
- Make code easier to read and maintain
- Break complex problems into smaller steps
- Reuse code across your program or even other programs
Quiz: Check Your Understanding
1. How do you define a function in Python?
a) function greet():
b) def greet():
c) func greet()
Answer: b) def greet():
2. What is the keyword to return a value from a function?
Answer: return
3. What will this code print?
def double(x):
return x * 2
print(double(4))
Answer: 8
4. True or False: Functions can have zero or more parameters.
Answer: True
Practice Exercise: Temperature Converter
Write a function called celsius_to_fahrenheit
that:
- Takes a temperature in Celsius as input
- Returns the temperature converted to Fahrenheit using the formula:
Fahrenheit = Celsius × 9/5 + 32
Then, write code to:
- Ask the user for a Celsius temperature
- Call the function
- Print the result
Starter code:
def celsius_to_fahrenheit(celsius):
return celsius * 9 / 5 + 32
temp_c = float(input("Enter temperature in Celsius: "))
temp_f = celsius_to_fahrenheit(temp_c)
print(f"{temp_c}°C is {temp_f}°F")