What if you never had to rewrite the same code twice?
That’s exactly what functions help you do.
So far, we’ve worked with data, logic, repetition, and text.
But as programs grow, writing everything step by step becomes messy.
That’s where functions come in.
A function is a block of code that performs a specific task. You define it once, and reuse it whenever needed.
🔹 Creating a Function
In Python, we use the keyword def to define a function.
def greet():
print("Hello, welcome!")
To use it, we call it:
greet()
🔹 Functions with Parameters
Functions become more powerful when they can accept input.
def greet(name):
print("Hello " + name)
greet("Mary")
Now the function can work with different names.
🔹 Functions with Multiple Inputs
You can pass more than one value into a function.
def add_numbers(a, b):
print(a + b)
add_numbers(5, 3)
This makes your code flexible and reusable.
🔹 Return Values
Sometimes you don’t just want to print a result you want to use it later.
That’s where return comes in.
def multiply(a, b):
return a * b
result = multiply(4, 5)
print(result)
Now the result can be stored and reused.
💡 Why Functions Matter
Functions help you:
- Avoid repeating code
- Organize your program better
- Make your code easier to read
- Reuse logic anywhere in your program In real applications, functions are everywhere. Without them, programs would be long, messy, and hard to manage.
🌱 Challenge
Write a function that:
- Takes a name and age as input
- Prints a sentence like: “My name is ___ and I am ___ years old” Then:
- Call the function at least 2 times with different values Try to think of it as building a small reusable tool.
Next, we’ll explore lambda functions, a shorter way of writing functions used in more advanced Python code.
Top comments (0)