Understanding Scopes: Local vs. Global Variables
Today, I delved into a fundamental aspect of Python programming – variable scopes. With a focus on distinguishing between local and global variables, I revisited a common stumbling block from past projects: defining global variables within functions.
The Pitfalls of Global Definitions
In this exploration, I uncovered the potential pitfalls of such practices, which can lead to confusion and unexpected behavior in code execution.
Embracing Encapsulation: Returning Variables from Functions
Instead, I adopted a best practice approach by emphasizing encapsulation and clarity in my code. By returning variables from functions rather than defining them globally, I enhance readability, maintainability, and minimize the risk of unintended side effects.
Guess The Number
Implementing Local and Global Variables in the Game
In the provided code, we can observe the usage of both local and global variables:
- Local Variables: Variables such as
lives
,random_number
,numbers_guessed
, andguess
are defined within functions (easy_mode()
andhard_mode()
). These variables are local to their respective functions and can only be accessed and modified within those functions. - Global Variables: The
playing
variable, used to control the main game loop, is defined outside of any function. It is a global variable accessible from any part of the script.
Guess The Number
How the Game Works:
The Guess-a-Number game follows a simple set of rules:
- The game randomly selects a number between 1 and 100.
- The player chooses the game mode: easy (with 10 guesses) or hard (with 5 guesses).
- The player inputs their guess for the randomly selected number.
- If the player’s guess matches the randomly selected number, they win the game.
- If the player’s guess is incorrect, they lose a life.
- The game continues until the player either guesses the correct number or runs out of lives.
Utilizing Local Variables for Game Logic
Within the game functions (easy_mode()
and hard_mode()
), local variables play a crucial role in implementing game logic. For example:
lives
: Tracks the number of lives the player has remaining.random_number
: Stores the randomly generated number that the player must guess.numbers_guessed
: Keeps track of the numbers guessed by the player to avoid duplicate guesses.guess
: Stores the user’s input for their guess.
These local variables are used to manage the game state, validate user input, and provide feedback to the player during gameplay.
The Code
import random
import os
def clear():
os.system('cls' if os.name == 'nt' else 'clear')
def lose_life(lives, random_number, numbers_guessed, guess):
if guess not in numbers_guessed and guess != random_number:
lives -= 1
numbers_guessed.append(guess)
print(f"You have {lives} lives left")
print(f"You have guessed: {numbers_guessed}")
print("__________________________________________________________")
elif guess in numbers_guessed:
print("You have already guessed that number")
print(f"You have {lives} lives left")
return lives, numbers_guessed
def easy_mode():
lives =10
random_number = random.randint(1, 100)
numbers_guessed = []
print("Welcome to Easy mode of the number guessing game!")
print("I'm thinking of a number between 1 and 100")
print(f"You have {lives} lives to guess the number!\n")
print("__________________________________________________________")
while lives > 0:
guess = int(input("Guess a number: "))
if guess == random_number:
print(f"Congratulations you guessed the number {random_number}!")
print("That was the correct number! You are a pro!")
print("Why not try hard mode next time?")
print("__________________________________________________________")
break
elif guess < random_number:
print("The number you guessed is too low")
elif guess > random_number:
print("The number you guessed is too high")
lives, numbers_guessed = lose_life(lives, random_number, numbers_guessed, guess)
if lives == 0:
print(f"You have run out of lives, the number was {random_number}")
input("\nPress enter to continue")
break
def hard_mode():
lives =5
random_number = random.randint(1, 100)
numbers_guessed = []
print("Welcome to Hard mode of the number guessing game!")
print("I'm thinking of a number between 1 and 100")
print(f"You have {lives} lives to guess the number!\n")
print("__________________________________________________________")
while lives > 0:
guess = int(input("Guess a number: "))
if guess == random_number:
print(f"Congratulations you guessed the number {random_number}!")
print("That was the correct number! You are a pro!")
print("__________________________________________________________")
break
elif guess < random_number:
print("The number you guessed is too low")
elif guess > random_number:
print("The number you guessed is too high")
lives, numbers_guessed = lose_life(lives, random_number, numbers_guessed, guess)
if lives == 0:
print(f"You have run out of lives, the number was {random_number}")
input("\nPress enter to continue")
break
def main():
logo ="""
_____ _____ _ _ _ _ _
| __ \ |_ _|| | | \ | | | | | |
| | \/ _ _ ___ ___ ___ | | | |__ ___ | \| | _ _ _ __ ___ | |__ ___ _ __ | |
| | __ | | | | / _ \/ __|/ __| | | | '_ \ / _ \ | . ` || | | || '_ ` _ \ | '_ \ / _ \| '__|| |
| |_\ \| |_| || __/\__ \\_ _ \ | | | | | || __/ | |\ || |_| || | | | | || |_) || __/| | |_|
\____/ \__,_| \___||___/|___/ \_/ |_| |_| \___| \_| \_/ \__,_||_| |_| |_||_.__/ \___||_| (_)
"""
print(logo)
print("Welcome to the number guessing game")
mode = input("Choose a mode (easy/hard): ")
clear()
if mode == "easy":
easy_mode()
elif mode == "hard":
hard_mode()
else:
print("Invalid mode")
main()
playing=True
while playing:
clear()
main()
if input("Would you like to play again? (yes/no): ") == "no":
playing = False
print("\nGoodbye")
input("\nPress enter to exit")
break
Python