What You Will Learn
A function is a reusable block of code that performs a specific task. Instead of writing the same code multiple times, you define it once and call it whenever you need it.
Defining a Function
Use def to define a function:
def greet():
print("Hello!")
print("Welcome to Python.")
greet()
greet()
Expected output:
Hello!
Welcome to Python.
Hello!
Welcome to Python.
Define the function once, call it as many times as you want.
Parameters — Giving Information to a Function
Parameters let you pass information into a function:
def greet(name):
print(f"Hello, {name}!")
greet("Alice")
greet("Bob")
Expected output:
Hello, Alice!
Hello, Bob!
name is a parameter — a variable that receives the value you pass when calling the function.
Multiple Parameters
def add(a, b):
print(f"{a} + {b} = {a + b}")
add(3, 4)
add(10, 25)
Expected output:
3 + 4 = 7
10 + 25 = 35
Return Values
A function can give back a result using return:
def add(a, b):
return a + b
result = add(3, 4)
print(result)
print(add(10, 25))
Expected output:
7
35
The returned value can be stored in a variable or used directly.
Default Parameters
You can give parameters default values:
def greet(name, greeting="Hello"):
print(f"{greeting}, {name}!")
greet("Alice")
greet("Bob", "Hi")
greet("Carol", greeting="Hey")
Expected output:
Hello, Alice!
Hi, Bob!
Hey, Carol!
If you do not pass a value for greeting, it uses the default "Hello".
Keeping Functions Small
Each function should do one thing. Here is a well-structured example:
def celsius_to_fahrenheit(celsius):
return celsius * 9 / 5 + 32
def fahrenheit_to_celsius(fahrenheit):
return (fahrenheit - 32) * 5 / 9
def show_conversion(celsius):
f = celsius_to_fahrenheit(celsius)
print(f"{celsius}°C = {f:.1f}°F")
show_conversion(0)
show_conversion(100)
show_conversion(37)
Expected output:
0°C = 32.0°F
100°C = 212.0°F
37°C = 98.6°F
What You Learned
defdefines a function- Parameters pass information into the function
returnsends a result back to the caller- Default parameters make arguments optional
- Functions should do one thing well
In the next lesson, you will learn about lists — one of Python’s most useful data structures.