🔁 Python Course in 4 to 6 Weeks – Lesson 10: Functions in Python
Welcome to Lesson 10 of our Python Course in 4 to 6 Weeks! In this lesson, you'll learn how to create and use functions — reusable blocks of code that make your programs more efficient, readable, and scalable.
✅ What You'll Learn
- What functions are and why we use them
- How to define and call functions
- Function parameters and return values
- Built-in vs. user-defined functions
- Scope and lifetime of variables
🛠️ Defining a Function
def greet():
print("Hello, Python!")
greet() # Call the function
📥 Parameters & Arguments
def greet_user(name):
print(f"Hello, {name}!")
greet_user("Amr")
🔄 Return Values
def add(a, b):
return a + b
result = add(5, 3)
print(result) # Output: 8
📚 Built-in Functions Examples
print(len("Python"))
print(max([1, 2, 3]))
print(type(42))
📦 Scope of Variables
- Local Scope: Inside the function only
- Global Scope: Outside the function
def show_name():
name = "Amr"
print(name)
show_name()
# print(name) # Error: name is not defined outside
⚠️ Common Mistakes
- ❌ Forgetting to call the function after defining it
- ❌ Confusing
print
withreturn
- ❌ Overwriting built-in function names like
sum
,input
🧪 Practice Challenge
Create a Python file named calculator.py
that:
- Defines functions for add, subtract, multiply, and divide
- Takes two numbers as input
- Performs and returns the results of each operation
📥 Tools You'll Need
- 🐍 Python: https://www.python.org/downloads/
- 📝 VS Code: https://code.visualstudio.com/
- 🌐 Replit: https://replit.com/languages/python3
📌 Final Words
Functions make your code cleaner, more organized, and easier to debug. As we move forward, you’ll use functions in nearly every Python project you build. In the next lesson, we’ll learn how to handle external files and store data in them.
🔗 Coming Next:
Lesson 11: File Handling – Read and Write Files in Python 📁