Functions
Functions
Defining Functions
def greet():
print("Hello!")greet() # Hello!
Functions with Parameters
def greet(name):
print(f"Hello, {name}!")greet("John") # Hello, John!
Default Parameters
def greet(name="Guest"):
print(f"Hello, {name}!")greet() # Hello, Guest!
greet("John") # Hello, John!
Return Values
def add(a, b):
return a + bresult = add(3, 5)
print(result) # 8
Multiple Return Values
def calculate(a, b):
return a + b, a - b, a * badd, sub, mul = calculate(10, 5)
print(add, sub, mul) # 15 5 50
args and *kwargs
# *args - variable positional arguments
def sum_all(*args):
return sum(args)print(sum_all(1, 2, 3, 4)) # 10
kwargs - variable keyword arguments
def print_info(kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")print_info(name="John", age=30)
name: John
age: 30
Lambda Functions
# Anonymous function
square = lambda x: x 2
print(square(5)) # 25With sorted
pairs = [(1, 'one'), (3, 'three'), (2, 'two')]
pairs.sort(key=lambda x: x[0])
Summary
- Functions: reusable code blocks
- Parameters: positional, default, args, *kwargs
- Return: single or multiple values
- Lambda: anonymous functions
Next Lesson
In the next lesson, you'll learn about modules and packages.
Quiz - Quiz - Functions
1. What keyword is used to define a function?
2. What does return statement do?
3. What is a lambda function?