You are viewing a free preview of this lesson.
Subscribe to unlock all 10 lessons in this course and every other course on LearningBro.
Functions are reusable blocks of code that perform a specific task. They help you organise your code, avoid repetition, and make programs easier to read, test, and maintain. Functions are one of the most important concepts in programming.
Use the def keyword:
def greet(name):
"""Greet a person by name."""
print(f"Hello, {name}!")
# Call the function
greet("Alice") # Hello, Alice!
greet("Bob") # Hello, Bob!
Anatomy of a function:
def — keyword to define a functiongreet — the function name(name) — parameter(s)""" docstring """ — optional documentationgreet("Alice")Functions can return values using the return statement:
def add(a, b):
"""Return the sum of a and b."""
return a + b
result = add(3, 5)
print(result) # 8
# Functions without return statement return None
def say_hello():
print("Hello!")
x = say_hello() # prints "Hello!"
print(x) # None
def get_stats(numbers):
"""Return the min, max, and average of a list."""
return min(numbers), max(numbers), sum(numbers) / len(numbers)
Subscribe to continue reading
Get full access to this lesson and all 10 lessons in this course.