chapter 7.1

Functions

Reusable blocks of logic

A function is a named block of code you can call whenever you need it. You've been using functions already — print(), len(), type() are all built-in functions. Now you'll write your own.
def greet(name):
    print(f"Hello, {name}!")

greet("Ada")     # Hello, Ada!
greet("Grace")   # Hello, Grace!
Parameters are the inputs a function accepts. Arguments are the actual values you pass in:
def add(a, b):      # a and b are parameters
    return a + b

result = add(3, 5)   # 3 and 5 are arguments
print(result)        # 8
warning
return vs print — the #1 beginner mistake. print() displays text but produces None. return sends a value back to the caller so you can use it. If you write print(x) instead of return x, your function "works" visually but you can't do anything with the result.
# WRONG — prints but returns None
def bad_add(a, b):
    print(a + b)

x = bad_add(3, 5)  # Prints "8" but...
print(x)            # None! Can't use it.

# RIGHT — returns the value
def good_add(a, b):
    return a + b

y = good_add(3, 5)
print(y * 2)        # 16 — now you can use it!
Default arguments give parameters a fallback value:
def power(base, exponent=2):
    return base ** exponent

print(power(5))      # 25 (defaults to squared)
print(power(5, 3))   # 125 (cubed)
Scope — variables inside a function are local and don't exist outside it:
def make_message():
    msg = "Hello from inside!"  # Local variable
    return msg

result = make_message()
print(result)    # Works fine
# print(msg)     # NameError! msg doesn't exist out here
Functions can call other functions — this is how you build complex behavior from simple pieces:
def is_even(n):
    return n % 2 == 0

def filter_evens(numbers):
    return [n for n in numbers if is_even(n)]

print(filter_evens([1, 2, 3, 4, 5, 6]))
# [2, 4, 6]
your turn
challenge

Write two functions: 1. `celsius_to_fahrenheit(celsius)` that **returns** the Fahrenheit value (formula: C × 9/5 + 32) 2. `classify_temp(f)` that **returns** a label: "cold", "cool", "warm", "hot", or "boiling" Then loop through a few temperatures and print the results.

loading editor...

output
$ Press RUN to execute your code
AI Tutor

Ask about Functions

Hey! I'm your AI tutor.

Ask me anything about this lesson, or paste code you're stuck on.

AI tutor is a premium feature