From Zero to Python Hero: Day 11 - The Number Guessing Game
Introduction
Greetings, fellow coding enthusiasts! Welcome back to my 100-day programming journey. On Day 11, I delved deeper into the Python programming language, exploring namespaces, scopes, and taking on the challenging Number Guessing Game project. It's been quite a ride, so let's get started!
Grasping Namespaces: Local vs. Global Scope
Think of Python as a sprawling city, where neighborhoods represent functions and code blocks. In this city, namespaces are like unique districts, each containing its variables and functions. Python primarily has two scopes: local and global.
Local Scope: Local scope is akin to a house within a neighborhood. Variables defined inside a function are local, meaning they can't be accessed from outside that function. Here's an example:
def my_function():
local_var = 42
return local_var
In this code, local_var
is confined within the boundaries of my_function
.
Global Scope: Global scope is like a central park, open to everyone. Variables declared outside of any function have global scope:
global_var = 100
def another_function():
return global_var
Here, global_var
is accessible from anywhere in your code.
Using Local and Global Scope:
x = 10 # Global variable
def my_function():
y = 5 # Local variable
return x + y # Accessing both global and local variables
result = my_function()
print(result) # Output: 15
Demonstrating Global Scope:
global_var = 50 # A global variable
def modify_global():
global global_var # Using the global keyword to access and modify the global variable
global_var += 10
modify_global()
print(global_var) # Output: 60
Does Python Have Block Scope?
No, Python does not have block scope as some other programming languages do. Variables declared inside code blocks (such as loops or conditional statements) have the same scope as the enclosing function. Here's an example:
def block_scope_example():
if True:
block_var = "I'm here!"
return block_var # This works because block_var is in the same function scope.
Modifying a Global Variable
To modify a global variable within a function, we need to use the global
keyword:
global_var = 100
def modify_global():
global global_var
global_var += 10
Modifying a Global Variable:
global_var = 100
def modify_global():
global global_var
global_var += 10
modify_global()
print(global_var) # Output: 110
Python Constants and Global Scope
Python doesn't have built-in constants like some other languages, but we often use uppercase variable names to indicate constants:
MY_CONSTANT = 3.14
These variables are still within the global scope.
The Number Guessing Game Project
Now, let's talk about the highlight of the day โ my mini-project, the Number Guessing Game! Here's the code:
from random import randint
EASY_LEVEL_TURNS = 10
HARD_LEVEL_TURNS = 5
#Function to check user's guess against actual answer.
def check_answer(guess, answer, turns):
"""checks answer against guess. Returns the number of turns remaining."""
if guess > answer:
print("Too high.")
return turns - 1
elif guess < answer:
print("Too low.")
return turns - 1
else:
print(f"You got it! The answer was {answer}.")
#Make function to set difficulty.
def set_difficulty():
level = input("Choose a difficulty. Type 'easy' or 'hard': ")
if level == "easy":
return EASY_LEVEL_TURNS
else:
return HARD_LEVEL_TURNS
def game():
#Choosing a random number between 1 and 100.
print("Welcome to the Number Guessing Game!")
print("I'm thinking of a number between 1 and 100.")
answer = randint(1, 100)
print(f"Pssst, the correct answer is {answer}")
turns = set_difficulty()
#Repeat the guessing functionality if they get it wrong.
guess = 0
while guess != answer:
print(f"You have {turns} attempts remaining to guess the number.")
#Let the user guess a number.
guess = int(input("Make a guess: "))
#Track the number of turns and reduce by 1 if they get it wrong.
turns = check_answer(guess, answer, turns)
if turns == 0:
print("You've run out of guesses, you lose.")
return
elif guess != answer:
print("Guess again.")
game()
In this game, I've applied the concepts of global and local scope to manage the secret number and the player's guess effectively. It's an engaging way to reinforce your Python skills!
Conclusion
That's a wrap for Day 11. We've covered Python namespaces, scopes, modifying global variables, constants, and had a blast with the Number Guessing Game project. Keep coding, keep learning, and stay tuned for more exciting Python adventures! ๐โจ