Skip to ContentGo to accessibility pageKeyboard shortcuts menu
OpenStax Logo

Learning objectives

By the end of this section you should be able to

  • Identify the scope of a program's variables.
  • Discuss the impact of a variable's scope.

Global scope

A variable's scope is the part of a program where the variable can be accessed. A variable created outside of a function has global scope and can be accessed anywhere in the program. A Python program begins in global scope, and the global scope lasts for the entire program execution.

Checkpoint

Global variables in a program with a function

Concepts in Practice

Global variables

1.
Which variables are global?
num = float(input())
num_sq = num * num
print(num, "squared is", num_sq)
  1. num only
  2. num_sq only
  3. num and num_sq
2.
Which variables have global scope?
def print_square():
  num_sq = num * num
  print(num, "squared is", num_sq)

num = float(input())
print_square()
  1. num only
  2. num_sq only
  3. num and num_sq
3.
Which functions can access num?
def print_double():
  num_d = num * 2
  print(num, "doubled is", num_d)

def print_square():
  num_sq = num * num
  print(num, "squared is", num_sq)

num = float(input())
print_double()
print_square()
  1. print_double()
  2. print_square()
  3. print_double() and print_square()

Local scope

A variable created within a function has local scope and only exists within the function. A local variable cannot be accessed outside of the function in which the variable was created. After a function finishes executing, the function's local variables no longer exist.

Checkpoint

Global and local variables in a program with a function

Concepts in Practice

Local variables

4.
Which variables are local?
def print_time():
  out_str = "Time is " + str(hour) + ":" + str(min)
  print(out_str)

hour = int(input())
min = int(input())
print_time()
  1. hour and min
  2. out_str
  3. hour, min, and out_str
5.
Which variables are local?
def print_greeting():
  print(out_str)

hour = int(input())
min = int(input())
if hour < 12:
  out_str = "Good morning"
else:
  out_str = "Good day"
print_greeting()
  1. hour and min
  2. out_str
  3. none
6.
Which functions directly access out_str?
def print_greeting():
  print("Good day,")
  print_time()

def print_time():
  out_str = "Time is " + str(hour) + ":" + str(min)
  print(out_str)

hour = int(input())
min = int(input())
print_greeting()
  1. print_greeting()
  2. print_time()
  3. print_greeting() and print_time()

Using local and global variables together

Python allows global and local variables to have the same name, which can lead to unexpected program behavior. A function treats a variable edited within the function as a local variable unless told otherwise. To edit a global variable inside a function, the variable must be declared with the global keyword.

Checkpoint

Editing global variables in a program with a function

Concepts in Practice

Using both local and global variables

Consider the following variations on the example program with the input 9.

7.
What is the output?
def update_hour():
  tmp = hour
  if is_dst:
    tmp += 1
  else:
    tmp -= 1

is_dst = True
hour = int(input("Enter hour: "))
update_hour()
print("New hour:", hour)
  1. New hour: 9
  2. New hour: 10
  3. Error
8.
What is the output?
def update_hour():
  new_hour = hour
  if is_dst:
    new_hour += 1
  else:
    new_hour -= 1

is_dst = True
hour = int(input("Enter hour: "))
update_hour()
print("New hour:", new_hour)
  1. New hour: 9
  2. New hour: 10
  3. Error
9.
What is the output?
def update_hour():
  global new_hour
  new_hour = hour
  if is_dst:
    new_hour += 1
  else:
    new_hour -= 1

is_dst = True
hour = int(input("Enter hour: "))
update_hour()
print("New hour:", new_hour)
  1. New hour: 9
  2. New hour: 10
  3. Error

Benefits of limiting scope

A programmer might ask, "Why not just make all variables global variables to avoid access errors?" Making every variable global can make a program messy. Ex: A programmer debugging a large program discovers a variable has the wrong value. If the whole program can modify the variable, then the bug could be anywhere in the large program. Limiting a variable's scope to only what's necessary and restricting global variable use make a program easier to debug, maintain, and update.

Try It

Battle royale game launch

Write a program that reads in a selected game mode and calls one of two functions to launch the game. If the input is "br", call battle_royale(). Otherwise, call practice().

battle_royale():

  • Reads in the number of players.
  • Computes the number of teammates still needed. A full team is 3 players.
  • Calls the function find_teammates() with the calculated number.
  • Prints "Match starting . . .".

practice():

  • Reads in a string representing the desired map.
  • Prints "Launching practice on [desired map]".

Note: find_teammates() is provided and does not need to be edited.

Given input:

    br
    1

The output is:

    Finding 2 players...
    Match starting...

Given input:

    p
    Queen's Canyon

The output is:

    Launching practice on Queen's Canyon
Citation/Attribution

This book may not be used in the training of large language models or otherwise be ingested into large language models or generative AI offerings without OpenStax's permission.

Want to cite, share, or modify this book? This book uses the Creative Commons Attribution License and you must attribute OpenStax.

Attribution information
  • If you are redistributing all or part of this book in a print format, then you must include on every physical page the following attribution:
    Access for free at https://openstax.org/books/introduction-python-programming/pages/1-introduction
  • If you are redistributing all or part of this book in a digital format, then you must include on every digital page view the following attribution:
    Access for free at https://openstax.org/books/introduction-python-programming/pages/1-introduction
Citation information

© Jul 30, 2024 OpenStax. Textbook content produced by OpenStax is licensed under a Creative Commons Attribution License . The OpenStax name, OpenStax logo, OpenStax book covers, OpenStax CNX name, and OpenStax CNX logo are not subject to the Creative Commons license and may not be reproduced without the prior and express written consent of Rice University.

This book utilizes the OpenStax Python Code Runner. The code runner is developed by Wiley and is All Rights Reserved.