Python Tutorial

Functions

Functions let you package up logic so you can reuse it without repeating yourself.

Defining a function

def greet(name):
    return f"Hello, {name}!"

print(greet("Ada"))

Default arguments

def greet(name, greeting="Hello"):
    return f"{greeting}, {name}!"

print(greet("Ada"))             # Hello, Ada!
print(greet("Ada", "Hi"))       # Hi, Ada!

Multiple return values

Python functions can return more than one value as a tuple.

def min_max(numbers):
    return min(numbers), max(numbers)

lowest, highest = min_max([4, 1, 9, 3])
print(lowest, highest)  # 1 9

Keyword arguments and *args / **kwargs

def describe_pet(name, animal="dog", **traits):
    print(f"{name} is a {animal}")
    for key, value in traits.items():
        print(f"  {key}: {value}")

describe_pet("Rex", animal="dog", color="brown", age=3)

You’ve now covered the basics — variables, control flow, and functions. From here, try writing a small script that combines all three, like a number-guessing game.