Skip to content
Python Programming

Functions in Python

Beginner Lesson 5 of 10

Functions are reusable blocks of code that perform specific tasks.

def greet(name):
"""Return a greeting message."""
return f"Hello, {name}!"
message = greet("Alice")
print(message) # Hello, Alice!
# Default parameters
def greet(name, greeting="Hello"):
return f"{greeting}, {name}!"
# Keyword arguments
greet(name="Bob", greeting="Hi")
# *args for variable positional arguments
def sum_all(*numbers):
return sum(numbers)
# **kwargs for variable keyword arguments
def print_info(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")
square = lambda x: x ** 2
print(square(5)) # 25
# Common use with map, filter
numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x**2, numbers))

Continue to Object-Oriented Programming →