27. Understanding the global Keyword

Quiz: 0/5

The global keyword in Python is used to declare that a variable inside a function refers to a variable defined in the global scope. This allows you to modify global variables from within a function. Without the global keyword, assigning a value to a variable inside a function will create a local variable, leaving the global variable unchanged.

Defining global variables

A global variable is defined outside of any function, making it accessible throughout the entire script. Functions can read global variables without any special declaration.

# Global variable
x = 10

def print_x():
    print(x)

print_x()  # Output: 10

In this example, x is a global variable, and the print_x() function accesses it directly without modification.

Modifying global variables with global

To modify a global variable inside a function, you must use the global keyword. Without it, Python will create a local variable instead of changing the global one.

# Global variable
counter = 0

def increment():
    global counter  # Declare that we want to use the global variable
    counter += 1    # Increment the global variable

increment()
print(counter)  # Output: 1

increment()
print(counter)  # Output: 2

Key Points in the Example:

  • The increment() function declares counter as global to indicate that changes should apply to the global variable.
  • Each call to increment() modifies the global counter variable, allowing changes to persist outside the function.

What happens without the global keyword?

If you attempt to assign a value to a variable inside a function without declaring it as global, Python will create a new local variable. The global variable will remain unchanged.

# Global variable
value = 5

def change_value():
    value = 10  # This creates a new local variable named 'value'
    print(value)

change_value()  # Output: 10
print(value)    # Output: 5 (the global variable remains unchanged)

Key points in the example:

  • The change_value() function creates a local variable value that temporarily shadows the global variable.
  • The global variable value remains unaffected when you print it after calling change_value().

Key takeaways

  1. Using global: The global keyword allows functions to modify a global variable.
  2. Local vs. Global Scope: Without global, assigning to a variable inside a function creates a local variable that does not affect the global variable.
  3. Best Practices:
    • Minimize the use of global variables to avoid unintended side effects.
    • Consider using function parameters and return values to pass data between functions.

Hands-On Practise

Exercise: Managing a global counter

You are tasked with creating a simple program that tracks the number of visitors to a website.

  1. Define a global variable named visitor_count and initialize it to 0.

  2. Write two functions:

    • increment_visitors(): This function should:
      • Use the global keyword to modify the global visitor_count.
      • Increment visitor_count by 1.
    • display_visitors(): This function should:
      • Print the current value of visitor_count.
  3. Call increment_visitors() three times to simulate three new visitors.

  4. Use display_visitors() to print the total number of visitors.

Output:

Quizzes: 0/5

Question 1:

What does the global keyword in Python do?

  • Creates a new global variable.
  • Indicates that a variable inside a function refers to a global variable.
  • Deletes a global variable.
  • Prevents a global variable from being modified.

Question 2:

What happens if you modify a global variable inside a function without using the global keyword?

  • The global variable is modified as expected.
  • A SyntaxError is raised.
  • A new local variable with the same name is created.
  • Python raises an UnboundLocalError.

Question 3:

Which of the following is a best practice when working with global variables?

  • Use global variables as much as possible to simplify code.
  • Avoid using global variables whenever possible.
  • Use global variables to store temporary data within functions.
  • Always declare global variables inside functions.

Question 4:

What will the following code output? counter = 5 def update_counter(): global counter counter += 3 update_counter() print(counter)

  • 5
  • 3
  • 8
  • Error

Question 5:

Which statement about local and global scope is correct?

  • A variable defined inside a function is global by default.
  • A global variable can be accessed and modified anywhere without restrictions.
  • A local variable can shadow a global variable with the same name.
  • The global keyword is used to create local variables inside a function.

Feedback

Share your thoughts about this lesson

Discussion

Please log in to create a discussion.
Previous lessonVariable Scopes in PythonNext lessonNested Functions and Nonlocal variables