Quick Info
- Topic: Functions in Python
- Target Audience: Beginners who know loops and if-else
- Goal: Understand why functions exist and how to write one
1. Introduction
“I used to write the same code over and over. Copy, paste, tweak one word. Then I learned about functions — and my code got 10x shorter. Here’s how they work and why I use them everywhere now.”
2. The Problem (Without Functions)
print("Hello, Ali!")
print("Hello, Sara!")
print("Hello, Ahmed!")
print("Hello, John!")
print("Hello, Emma!")
Enter fullscreen mode Exit fullscreen mode
Problem: If I want to change “hello” to “hi”, I have to edit 5 lines. Imagine 100 lines
3. The Solution (With Functions)
def greet(name):
return f"Hello, {name}!"
print(greet("Ali"))
print(greet("Sara"))
print(greet("Ahmed"))
print(greet("John"))
print(greet("Emma"))
Enter fullscreen mode Exit fullscreen mode
Output:
Hello, Ali!
Hello, Sara!
Hello, Ahmed!
Hello, John!
Hello, Emma!
Enter fullscreen mode Exit fullscreen mode
4. How it works (Line by Line)
Line 1: def greet(name): — This defines a function called greet that takes one input: name.
Line 2: return f"Hello, {name}!" — This returns a greeting with the name inserted.
Line 4: print(greet("Ali")) — This calls the function with “Ali” and prints the result.
5. Real Example (My Practise)
python
def add_numbers(a, b):
return a + b
result = add_numbers(5, 3)
print(result)
Enter fullscreen mode Exit fullscreen mode
Output:
8
Enter fullscreen mode Exit fullscreen mode
6. What I learned
- Functions let me reuse code instead of repeating it
- def starts a function
- return sends the value back
- I can pass argument(inputs) into a functions
- If I need to change behavior, I change it in one place
Conclusion
Functions seemed like extra work at first. Now I can’t write code without them. They made my scripts cleaner, shorter, and easier to fix.