Loading...

Python Scope

A name the function sets belongs to that call. When the call ends, the name is gone. Scope is the stretch where a name can be seen. mark sets cups to 2 and prints cups. After mark(), cups is not a name you can use.

The print is indented four spaces, so it belongs to mark. The call is the line mark() with nothing indented.

cups exists only inside the call

python
def mark():
    cups = 2
    print(cups)

mark()

The screen shows 2. That 2 was written while the call was running. Add print(cups) after mark() and the program stops. cups ended with the call. The stop is not a bad indent. The name is simply not there.

A name set outside the function can be read inside, when the function does not set that same name. drink = "tea" sits level with def. If mark only prints drink, both prints read that one name. The screen shows tea, then tea.

Set the same name inside the function and you get a second name. It is the one the call sees. The outside name stays as it was.

The inside drink is a second name

python
drink = "tea"

def mark():
    drink = "water"
    print(drink)

mark()
print(drink)

The screen shows water, then tea. The indented print wrote water. The print level with def wrote tea. drink = "water" did not change the outside name. For this call, the inside drink is water. After the call, the drink you still have is tea.

Two misses

Printing cups after the first program stops the program. That name was born inside mark and died with the call. Reading the second screen as if the outside drink became water is the other miss. The second line is tea. Delete drink = "water" and leave the indented print(drink). Then there is only the outside name, and the screen shows tea, then tea. The program does not stop.

The next page is a function written on one line. This page is only about where a name can be seen.

Before you answer

  1. What does the first program write?
  2. You add print(cups) after mark() in the first program. Does the program finish?
  3. What does the second program write, first line then second?
  4. You delete drink = "water" and leave print(drink) inside mark. What is written?
  5. In the second program, which drink is water?

Where the name is

mark sets cups to 2 and prints it, so the first screen is 2. After that call, cups is not a name, and print(cups) stops the program. An outside drink = "tea" can be read inside if mark does not set drink. drink = "water" inside the call is a second name: the screen shows water, then tea, and the outside drink is still tea.

🧠 Test Your Knowledge

Ready to Start

Test Your Knowledge

Challenge yourself with this interactive quiz and see how well you understand the topic

❓
6
Questions
🎯
70%
To Pass
♾️
∞
Time
🔄
∞
Attempts

📝 Instructions

  • Read each question carefully
  • Select the best answer for each question
  • You can retake the quiz as many times as you want
  • Your progress will be shown at the top