47 lines
1.7 KiB
Python
47 lines
1.7 KiB
Python
|
|
|
|
"""
|
|
This script demonstrates the use of global variables and the `global` keyword in Python functions.
|
|
Global Variables:
|
|
- `age`: An integer representing a person's age.
|
|
Functions:
|
|
- birthday_greet():
|
|
- First definition: Prints a birthday greeting using the global `age` variable, incremented by 1 (without modifying the global variable).
|
|
- Second definition: Uses the `global` keyword to modify the global `age` variable by incrementing it by 1, then prints a birthday greeting.
|
|
- birthday_greet_global():
|
|
- First definition: Prints a birthday greeting using the global `age` variable, incremented by 5 (without modifying the global variable).
|
|
- Second definition: Uses the `global` keyword to modify the global `age` variable by incrementing it by 5, then prints a birthday greeting.
|
|
Demonstrates:
|
|
- The difference between accessing and modifying global variables inside functions.
|
|
- The effect of the `global` keyword on variable scope and assignment.
|
|
"""
|
|
age = 24
|
|
|
|
def birthday_greet():
|
|
print(f"Happy B-Day! You are {age + 1}! (local message)")
|
|
|
|
birthday_greet() # Call the local function
|
|
print("Global message", age) # Print the global variable
|
|
|
|
def birthday_greet_global():
|
|
print(f"Happy B-Day! You are {age + 5}! (global message)")
|
|
birthday_greet_global() # Call the global function
|
|
|
|
|
|
|
|
age = 20
|
|
|
|
def birthday_greet():
|
|
global age # Added 'global' keyword
|
|
age += 1
|
|
print(f"Happy B-Day! You are {age}! (local message)")
|
|
|
|
birthday_greet()
|
|
print("Global message", age)
|
|
|
|
def birthday_greet_global():
|
|
global age # Added 'global' keyword
|
|
age += 5
|
|
print(f"Happy B-Day! You are {age}! (global message)")
|
|
|
|
birthday_greet_global() # Call the global function |