Skip to main content
Engineering LibreTexts

6.3: Variable Scope

  • Page ID
    117558
  • \( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \)

    \( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)

    \( \newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\)

    ( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\)

    \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\)

    \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\)

    \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\)

    \( \newcommand{\Span}{\mathrm{span}}\)

    \( \newcommand{\id}{\mathrm{id}}\)

    \( \newcommand{\Span}{\mathrm{span}}\)

    \( \newcommand{\kernel}{\mathrm{null}\,}\)

    \( \newcommand{\range}{\mathrm{range}\,}\)

    \( \newcommand{\RealPart}{\mathrm{Re}}\)

    \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\)

    \( \newcommand{\Argument}{\mathrm{Arg}}\)

    \( \newcommand{\norm}[1]{\| #1 \|}\)

    \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\)

    \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\AA}{\unicode[.8,0]{x212B}}\)

    \( \newcommand{\vectorA}[1]{\vec{#1}}      % arrow\)

    \( \newcommand{\vectorAt}[1]{\vec{\text{#1}}}      % arrow\)

    \( \newcommand{\vectorB}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \)

    \( \newcommand{\vectorC}[1]{\textbf{#1}} \)

    \( \newcommand{\vectorD}[1]{\overrightarrow{#1}} \)

    \( \newcommand{\vectorDt}[1]{\overrightarrow{\text{#1}}} \)

    \( \newcommand{\vectE}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash{\mathbf {#1}}}} \)

    \( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \)

    \( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)

    \(\newcommand{\avec}{\mathbf a}\) \(\newcommand{\bvec}{\mathbf b}\) \(\newcommand{\cvec}{\mathbf c}\) \(\newcommand{\dvec}{\mathbf d}\) \(\newcommand{\dtil}{\widetilde{\mathbf d}}\) \(\newcommand{\evec}{\mathbf e}\) \(\newcommand{\fvec}{\mathbf f}\) \(\newcommand{\nvec}{\mathbf n}\) \(\newcommand{\pvec}{\mathbf p}\) \(\newcommand{\qvec}{\mathbf q}\) \(\newcommand{\svec}{\mathbf s}\) \(\newcommand{\tvec}{\mathbf t}\) \(\newcommand{\uvec}{\mathbf u}\) \(\newcommand{\vvec}{\mathbf v}\) \(\newcommand{\wvec}{\mathbf w}\) \(\newcommand{\xvec}{\mathbf x}\) \(\newcommand{\yvec}{\mathbf y}\) \(\newcommand{\zvec}{\mathbf z}\) \(\newcommand{\rvec}{\mathbf r}\) \(\newcommand{\mvec}{\mathbf m}\) \(\newcommand{\zerovec}{\mathbf 0}\) \(\newcommand{\onevec}{\mathbf 1}\) \(\newcommand{\real}{\mathbb R}\) \(\newcommand{\twovec}[2]{\left[\begin{array}{r}#1 \\ #2 \end{array}\right]}\) \(\newcommand{\ctwovec}[2]{\left[\begin{array}{c}#1 \\ #2 \end{array}\right]}\) \(\newcommand{\threevec}[3]{\left[\begin{array}{r}#1 \\ #2 \\ #3 \end{array}\right]}\) \(\newcommand{\cthreevec}[3]{\left[\begin{array}{c}#1 \\ #2 \\ #3 \end{array}\right]}\) \(\newcommand{\fourvec}[4]{\left[\begin{array}{r}#1 \\ #2 \\ #3 \\ #4 \end{array}\right]}\) \(\newcommand{\cfourvec}[4]{\left[\begin{array}{c}#1 \\ #2 \\ #3 \\ #4 \end{array}\right]}\) \(\newcommand{\fivevec}[5]{\left[\begin{array}{r}#1 \\ #2 \\ #3 \\ #4 \\ #5 \\ \end{array}\right]}\) \(\newcommand{\cfivevec}[5]{\left[\begin{array}{c}#1 \\ #2 \\ #3 \\ #4 \\ #5 \\ \end{array}\right]}\) \(\newcommand{\mattwo}[4]{\left[\begin{array}{rr}#1 \amp #2 \\ #3 \amp #4 \\ \end{array}\right]}\) \(\newcommand{\laspan}[1]{\text{Span}\{#1\}}\) \(\newcommand{\bcal}{\cal B}\) \(\newcommand{\ccal}{\cal C}\) \(\newcommand{\scal}{\cal S}\) \(\newcommand{\wcal}{\cal W}\) \(\newcommand{\ecal}{\cal E}\) \(\newcommand{\coords}[2]{\left\{#1\right\}_{#2}}\) \(\newcommand{\gray}[1]{\color{gray}{#1}}\) \(\newcommand{\lgray}[1]{\color{lightgray}{#1}}\) \(\newcommand{\rank}{\operatorname{rank}}\) \(\newcommand{\row}{\text{Row}}\) \(\newcommand{\col}{\text{Col}}\) \(\renewcommand{\row}{\text{Row}}\) \(\newcommand{\nul}{\text{Nul}}\) \(\newcommand{\var}{\text{Var}}\) \(\newcommand{\corr}{\text{corr}}\) \(\newcommand{\len}[1]{\left|#1\right|}\) \(\newcommand{\bbar}{\overline{\bvec}}\) \(\newcommand{\bhat}{\widehat{\bvec}}\) \(\newcommand{\bperp}{\bvec^\perp}\) \(\newcommand{\xhat}{\widehat{\xvec}}\) \(\newcommand{\vhat}{\widehat{\vvec}}\) \(\newcommand{\uhat}{\widehat{\uvec}}\) \(\newcommand{\what}{\widehat{\wvec}}\) \(\newcommand{\Sighat}{\widehat{\Sigma}}\) \(\newcommand{\lt}{<}\) \(\newcommand{\gt}{>}\) \(\newcommand{\amp}{&}\) \(\definecolor{fillinmathshade}{gray}{0.9}\)
    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
  • num_sq only
  • 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
  • out_str
  • 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
  • New hour: 10
  • 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

    This page titled 6.3: Variable Scope is shared under a CC BY 4.0 license and was authored, remixed, and/or curated by OpenStax via source content that was edited to the style and standards of the LibreTexts platform.