Python Functions
A function is a reusable block of code that performs a specific task. It helps you organize your code, avoid repetition, and make programs more readable and modular.
Python Functions
✨ Benefits of Using Functions
- Write code once, reuse it anywhere
- Makes debugging and testing easier
- Improves readability and structure
- Breaks complex problems into smaller steps
🧱 Structure of a Python Function
1
2
3
def function_name(parameters):
# code block
return result # optional
✅ Example 1: Basic Function (No Parameters)
1
2
3
4
def greet():
print("Hello!")
greet() # Call the function
📤 Output:
1
Hello!
✅ Example 2: Function With Parameters
1
2
3
4
5
def greet(name):
print("Hello, " + name + "!")
greet("Alice")
greet("Ivan")
📤 Output:
1
2
Hello, Alice!
Hello, Ivan!
✅ Example 3: Function With Return Value
1
2
3
4
5
def add(a, b):
return a + b
result = add(3, 5)
print("The sum is:", result)
📤 Output:
1
The sum is: 8
🔁 Example 4: Using a Function in a Loop
1
2
3
4
5
def square(x):
return x * x
for i in range(5):
print(square(i))
📤 Output:
1
2
3
4
5
0
1
4
9
16
🧠 Notes
- Use
def
to define a function. - Use
return
to send back a result. - Functions can take 0 or more arguments.
- You can call a function as many times as needed.
🛠️ Optional: Default Parameter Values
1
2
3
4
5
def greet(name="friend"):
print("Hello, " + name)
greet() # Uses default
greet("David") # Overrides default
📤 Output:
1
2
Hello, friend
Hello, David
This post is licensed under
CC BY 4.0
by the author.