Warmup

  • Write a function that accepts a first and last and returns the full name as one string. Add an optional parameter "last_first" with a default value of False
  • If caller passes True for this value, the returned string should have the format <Last>, <First>

Agenda

  • Lesson 4.3 (Variable Scope)

Reminders:

  • PE1 Module 4 (Quiz due Thurs, Test due Fri)
  • Unit quiz on Friday via Canvas Quizzes

Lesson 4.3: Scope

Review

  • Functions let us organize code into reusable blocks
  • Parameters bring data into a function
  • Functions return data back out

What is Scope?

  • Scope = where a variable can be accessed in a program
  • Two main kinds in Python:
    • Local scope: inside a function
    • Global scope: outside all functions

Local Scope

  • Variables created inside a function exist only inside it
def example():
    x = 10  # local variable
    return x

print(example())
# print(x)  # ERROR: x not defined here

Global Scope

  • Variables defined outside functions are global
  • Can be accessed inside functions (but usually not changed)
y = 5

def show():
    return y

print(show())  # 5

Shadowing

  • A local variable with the same name as a global one will shadow it
z = 100

def shadow():
    z = 50  # local z
    return z

print(shadow())  # 50
print(z)         # 100

The global Keyword

  • Forces a function to change a global variable
  • Not recommended (can make code hard to test/debug)
count = 0

def bad():
    global count
    count += 1

bad()
print(count)  # 1

Why Globals Are Risky

  • Harder to test functions
  • Changes can affect other parts of the program
  • Better: pass values in and return results

Quick Check

  • What is the difference between local and global scope?
  • What does it mean when a variable is shadowed?
  • Why should we avoid changing globals inside functions?

Practice Challenge

Write a function counter(n) that takes a number and returns it increased by 1.

  • Don’t use global variables!