As you write more code, you’ll notice that some parts of your code repeat. Instead of writing the same thing again and again, we can group that code into something called a function.
Functions let you give a name to a block of code. Later, you can use that name to run the code whenever you want — as many times as you want!
Why Do We Need Functions?
- To avoid repeating the same code again and again.
- To make our code clean and easy to understand.
- To organize code into smaller, manageable pieces.
Basic Syntax of a Function
This is how you define a simple function in Python:
def function_name():
# block of code
print("Hello!")
Explanation:
def
is a keyword used to define a function.function_name
is the name you choose for your function (no spaces, only letters, numbers, and underscores).()
is where we can pass information (called parameters) — more on that below.- The code inside the function is written with indentation (usually 4 spaces).
How to Call (Use) a Function
Once the function is defined, you can use it like this:
def say_hello():
print("Hello!")
say_hello()
Hello!
Explanation: The line say_hello()
tells Python to run the code inside the function.
Functions with Parameters (Inputs)
You can also send information to a function by using parameters:
def greet(name):
print("Hello, " + name + "!")
greet("Arjun")
greet("Bob")
Hello, Arjun!
Hello, Bob!
Explanation: The word you pass inside greet()
goes into the name
variable inside the function.
Functions That Return a Value
Sometimes you want a function to calculate and give back a value. For that, we use the return
keyword:
def add(a, b):
return a + b
result = add(3, 4)
print(result)
7
Explanation: The function add()
calculates 3 + 4
and returns 7
, which we print.
Different Types of Functions
- No input, no return: Just does something like print
- With input, no return: Takes input and prints result
- With input and return: Takes input and gives back result
Examples of All Types
# No input, no return
def show_message():
print("Welcome!")
# Input, no return
def greet_user(name):
print("Hi, " + name)
# Input and return
def multiply(x, y):
return x * y
# Using the functions
show_message()
greet_user("Zara")
print(multiply(3, 5))
Welcome!
Hi, Zara
15
Conclusion
Functions are like mini-programs inside your main program. You can call them whenever you need them. This makes your code easier to read, write, and fix.
Comments
Loading comments...