You are viewing a free preview of this lesson.
Subscribe to unlock all 10 lessons in this course and every other course on LearningBro.
A function is a named, reusable block of code that performs a specific task. Functions help you avoid repetition, organise your code, and make it easier to test and maintain.
Use the def keyword:
def greet(name):
message = f"Hello, {name}!"
return message
result = greet("Alice")
print(result) # Hello, Alice!
The function body is indented. return sends a value back to the caller. Calling the function by name with parentheses executes it.
Parameters are variables listed in the function definition. Arguments are the actual values passed when calling the function:
def add(a, b):
return a + b
print(add(3, 4)) # 7
print(add(10, -2)) # 8
You can provide defaults so parameters become optional:
def greet(name, greeting="Hello"):
return f"{greeting}, {name}!"
print(greet("Alice")) # Hello, Alice!
print(greet("Bob", "Good morning")) # Good morning, Bob!
Call functions with argument names for clarity:
def describe_pet(name, species):
print(f"{name} is a {species}")
describe_pet(species="cat", name="Whiskers")
A function can return any value — or nothing (implicitly returns None):
def square(x):
return x * x
def say_hello():
print("Hello!") # returns None
result = square(5) # 25
You can return multiple values as a tuple:
def min_max(numbers):
return min(numbers), max(numbers)
low, high = min_max([3, 1, 7, 2, 9])
print(low, high) # 1 9
Variables created inside a function are local — they only exist within that function:
def my_function():
local_var = 10
print(local_var) # 10
my_function()
# print(local_var) # NameError — not accessible here
Variables defined outside functions are global:
PI = 3.14159
def circle_area(radius):
return PI * radius ** 2
print(circle_area(5)) # 78.53975
Document your functions with a docstring — a string literal on the first line of the body:
def celsius_to_fahrenheit(c):
"""Convert Celsius to Fahrenheit and return the result."""
return c * 9 / 5 + 32
help(celsius_to_fahrenheit)
For variable numbers of arguments:
def total(*args):
return sum(args)
print(total(1, 2, 3, 4)) # 10
def show_info(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")
show_info(name="Alice", age=30)
Functions are the building blocks of well-structured programs. Well-named, focused functions make code dramatically easier to read and debug.
Subscribe to continue reading
Get full access to this lesson and all 10 lessons in this course.