Navigating Variable Scopes: Local vs. Global in a Python Guess-a-Number Game
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
PythonBlackjack Capstone Project
Blackjack Capstone Project Embarking on day 11 of the 100 days of code challenge, I find myself reflecting on the journey I've taken with my Blackjack Capstone project. This update marks a...
Haunted Hotel game
Welcome to the Heart of the Haunting Step behind the curtain and explore the intricate design of the haunted hotel game, a project sparked by the imagination of two girls I was...
Discover Your Brain Type with the Brain Type Quiz
Introduction: Welcome to the Brain Type Quiz, a unique journey inspired by a YouTube short video. As an avid learner, I stumbled upon a fascinating quiz that determines one's brain type, sparking...
Title: Day 9: 100 Days of Code
Introduction: Today's journey in the 100 Days of Code challenge brought me face to face with the power of dictionaries and the intricacies of nesting them within each other, alongside lists. The...
Day 8: Caesar Cipher 100 Days of Code
Introduction Welcome to Day 8 of the 100 Days of Code challenge! Today's focus was on understanding functions, particularly defining and calling them. Let's dive into what I've learned and implemented. Caesar...
Day 6 + Day 7 Hangman Project
Day 6: Mastering Functions in Python Day six of my coding journey with Udemy's "100 Days of Code" course was dedicated to mastering functions in Python. Functions are powerful tools that allow...
Day 5: Mastering Loops
Mastering Loops Today, I delved into the fascinating world of loops in Python, a fundamental concept essential for automating repetitive tasks. I had the opportunity to create a program for the classic...
Day 4: Exploring Lists and Imports in Python
Day 4: Exploring Lists in Python Today, I delved into the fundamentals of lists in Python, a versatile data structure capable of holding multiple items in a single variable. Let's dive into...
Day 3: Exploring Python Statements and Projects
Day 3: Exploring Python Statements and Projects Today, on the third day of our coding journey with Python, we delved deeper into the realm of Python statements, logical operators, and comparison operators....