Functions

CDS1010: Week 5 Mini-Lecture
Wiedemann • Fall 2025

Why Functions?

  • Break big problems into smaller steps
  • Reduce repetition (DRY)
  • Improve readability and testing

Defining a Function

  • def introduces a function definition
  • Parameters are inputs; body runs when called
  • Use return to send a value back
def add(a, b):
    total = a + b
    return total

x = add(3, 4)
print(x)  # 7

return vs print

  • return gives data where the function was called
  • print shows text on screen for humans
  • Rule of thumb: compute with returns, communicate with prints
def add(a, b):
    total = a + b
    return total
                
x = add(3, 4)  # Nothing is printed; the return value is stored in x
print(x)       # 7 is printed

Scope: Where Names Live

  • Names inside a function are local to that function
  • Reading a global variable is allowed, but assigning creates a local variable
  • Prefer passing values in and returning values out
x = 10  # global variable (can be accessed anywhere)

def bump(x):
    x = x + 1  # local variable (only exists inside the function)
    return x

print(bump(10))  # 11 (the local variable is returned)
print(x)         # 10 (the global variable is unchanged)