Welcome to your Python Functions crash course! This lesson will walk you through the basics of creating and using functions in Python. Simple language, simple code, powerful skills.
A function is a block of code that only runs when it's called. You can pass data into a function, and it can return data as a result.
- Keeps your code organized
- Avoids repetition (DRY principle: Don't Repeat Yourself)
- Makes code easier to read and debug
- Helps with reusability in larger programs
By the end of this, you’ll be able to:
- Write your own functions
- Use arguments and return values
- Understand function scope
- Use default, variable, and keyword arguments
- Work with small extras like
lambdaand decorators
- Basic Function
- Arguments
- Return Values
- Default Arguments
- *args and **kwargs
- Lambda Functions
- Function Scope
- Decorators (Intro)
- Practice Exercises
- More Learning Links
def greet():
print("Hello, world!")
greet()def greet_user(name):
print("Hello, " + name)
greet_user("Sarah")def add(a, b):
return a + b
result = add(5, 3)
print(result)def greet(name="friend"):
print("Hello, " + name)
greet()
greet("Lerato")def total(*numbers):
print(sum(numbers))
total(2, 4, 6)
def print_info(**info):
print(info)
print_info(name="Alex", age=30)square = lambda x: x * x
print(square(4))def show():
message = "Hello inside"
print(message)
show()
# print(message) # This will give an error – variable not available outside the functiondef decorator(func):
def wrapper():
print("Before the function runs")
func()
print("After the function runs")
return wrapper
@decorator
def say_hi():
print("Hi!")
say_hi()Try writing these on your own:
- A function to multiply two numbers
- A function that returns "Even" or "Odd" based on a number
- A function that greets a list of names
- A function that calculates the factorial of a number using recursion
- A lambda function that adds 10 to a given number
- Python Docs – Functions
- W3Schools – Python Functions
- Real Python – Functions Guide
- Programiz – Python Functions
- GeeksForGeeks – Python Functions
Functions are your first real tool to write smarter Python. Master them early, and everything else becomes easier.
Happy coding! 🚀