In Python, a function is like a “recipe” that tells the computer what steps to perform when you “call” it. Functions allow us to:
- Group related lines of code together.
- Reuse code easily.
- Make programs organized and easier to read.
Creating a Function
To create a function in Python, you use the def
keyword. Here’s the basic structure:
def function_name():
# Code inside the function
print("Hello from the function!")
Explanation:
def
tells Python that you’re defining a function.function_name
is the name of your function (you can pick any name, but no spaces!).()
follows the name and can hold “inputs” (explained later).- Inside the function, you write the steps (or instructions) for the computer.
Example 1: A Simple Function
Let’s write a simple function to print “Welcome to Python!”.
def greet():
print("Welcome to Python!")
How to Use the Function
You need to call the function to make it run:
greet()
Output:
Welcome to Python!
Functions with Parameters (Inputs)
Parameters let you give extra information to a function. Think of it like adding ingredients to a recipe.
Example 2: A Function with One Parameter
Let’s make a function that greets a person by name.
def greet_person(name):
print(f"Hello, {name}! How are you?")
How to Call the Function:
You provide the name when calling the function:
greet_person("Alice")
greet_person("Bob")
Output:
Hello, Alice! How are you?
Hello, Bob! How are you?
Explanation:
name
is a parameter (a placeholder for input).f"..."
is used to insert the value ofname
into the string.
Functions with Multiple Parameters
You can add more parameters if needed.
Example 3: A Function with Two Parameters
Let’s create a function to calculate the total price after adding tax.
def calculate_price(price, tax_rate):
total = price + (price * tax_rate)
print(f"The total price is {total:.2f}")
How to Call the Function:
calculate_price(100, 0.15)
calculate_price(200, 0.20)
Output:
The total price is 115.00
The total price is 240.00
Explanation:
price
andtax_rate
are inputs.- The function calculates the total price and shows it formatted to 2 decimal places (
:.2f
).
Returning a Value from a Function
Sometimes, you don’t want to just print()
the result but want to return it for use later.
Example 4: A Function that Returns a Value
Let’s return the total price instead of printing it.
def calculate_price(price, tax_rate):
total = price + (price * tax_rate)
return total
How to Use the Returned Value:
result = calculate_price(100, 0.15)
print(f"The total price is {result:.2f}")
Output:
The total price is 115.00
Default Parameters
You can set default values for parameters. If no value is provided, the function uses the default.
Example 5: A Function with Default Parameters
Let’s assume the default tax rate is 10%.
def calculate_price(price, tax_rate=0.10):
total = price + (price * tax_rate)
return total
How to Call the Function:
print(calculate_price(100)) # Uses default tax rate of 10%
print(calculate_price(100, 0.20)) # Uses provided tax rate of 20%
Output:
110.0
120.0
Functions with Loops
Functions can have loops to repeat actions.
Example 6: A Function to Print a Message Multiple Times
def repeat_message(message, times):
for _ in range(times):
print(message)
How to Call the Function:
repeat_message("Hello!", 3)
Output:
Hello!
Hello!
Hello!
Combining Functions
Functions can call other functions!
Example 7: Combining Two Functions
def greet(name):
return f"Hello, {name}!"
def farewell(name):
return f"Goodbye, {name}!"
def conversation(name):
print(greet(name))
print("It's nice to meet you.")
print(farewell(name))
How to Call the Combined Function:
conversation("Alice")
Output:
Hello, Alice!
It's nice to meet you.
Goodbye, Alice!
Practical Example: A Simple Calculator
Let’s create a calculator that can add, subtract, multiply, or divide two numbers.
def calculator(a, b, operation):
if operation == "add":
return a + b
elif operation == "subtract":
return a - b
elif operation == "multiply":
return a * b
elif operation == "divide":
return a / b
else:
return "Invalid operation"
How to Use the Calculator:
print(calculator(10, 5, "add"))
print(calculator(10, 5, "subtract"))
print(calculator(10, 5, "multiply"))
print(calculator(10, 5, "divide"))
print(calculator(10, 5, "unknown"))
Output:
15
5
50
2.0
Invalid operation