Days 11 and 12 were filled with challenges, especially regarding using the local and global variables correctly. It can quickly get messy if we don’t keep track of everything. Working with local and global variables can be challenging, and it's easy to run into issues if we don't manage them carefully.
Learning outcomes:
Namespace: local and global variables
Return statement with local and global variables
Global constants
Final Projects:
Blackjack
Play the game via my replit account.
Click on the green button “Run” to start the game!
Number guessing game
Play the game via my replit account.
Click on the green button “Run” to start the game!
Key takeaway:
The Blackjack project was a bit difficult, so I decided to write down the game's requirements and write the code for each of them, one by one. After that I cleaned the code and wrapped everything in functions.
Namespace: local and global variables
Namespace:
A namespace is a container that holds a set of identifiers (variables, functions, classes, etc.) and their associated objects. Namespaces help in organizing and managing the names of objects to prevent naming conflicts.
Each Python program has multiple namespaces, and they are organized in a hierarchical structure, with the global namespace at the top: there is one global namespace for the entire module, and each function call creates a local namespace.
The global namespace is accessible from any part of the module, while local namespaces are limited to the function in which they are defined.
Local variables:
Local variables are variables that are defined within a specific function.
They exist only for the duration of the function's execution and are destroyed when the function exits.
Local variables can have the same name as global variables, within the local scope.
Example:
x = 10 # Global variable
def my_function():
y = 5 # Local variable
print(x) # Accessing the global variable is possible
print(y) # Accessing the local variable
my_function()
print(x) # Accessing the global variable is possible
print(y) # Attempting to access the local variable here would result in an error
Global variables:
Global variables are variables that are defined at the top level of a Python module. They have global scope and can be accessed from anywhere.
Global variables are declared outside of any function, and their values remain throughout the program's execution.
Local variables with the same name as a global variable can temporarily "shadow" the global variable within a local scope.
Example:
x = 10 # Global variable
def my_function():
x = 5 # Local variable that shadows the global variable
print(x) # Accessing the local variable
my_function()
print(x) # Accessing the global variable
Return statement with local and global variables
Returning local variables:
If we want to return a local variable's value from a function, we can use the
return
statement to send that value back to the caller.The caller can then capture and use the returned value.
Example:
def calculate_sum(a, b):
result = a + b # 'result' is a local variable
return result # Return the local variable 'result'
total = calculate_sum(5, 3)
print(total) # 'total' captures the returned value (local variable created inside the function)
Returning global variables:
If we want to return a global variable's value from a function, we can simply reference the global variable and return its value.
The global variable's value can then be used by the caller.
Example:
global_variable = 42 # 'global_variable' is a global variable
def get_global():
return global_variable # Return the global variable
value = get_global()
print(value) # 'value' captures the returned value
In both cases, the return
statement is used to send the value of a variable, whether local or global, back to the calling function. The key distinction is whether the variable was defined and assigned within the local scope of a function (local variable) or at the global scope (global variable).
It's important to note that modifying a global variable's value within a function requires using the global
keyword to explicitly indicate that the variable being modified is a global variable. Otherwise, Python will create a new local variable with the same name within the function's scope.
Example:
x = 10 # This is a global variable
def modify_global_variable():
global x # Use the 'global' keyword to specify that we want to modify the global 'x' variable
x = 20
modify_global_variable()
print(x) # This will output 20 because we modified the global variable 'x' within the function.
Global constants
Variables in Python with fixed values that remain constant throughout the program. They are defined at the top level and are typically named in uppercase letters to indicate their constant nature. Global constants are used to store values that should not be modified during the program's execution.
Final projects
1/ Number guessing game
Below is my first attempt for this simple program: guessing a number, generated randomly between 1 and 100. There are two levels: easy and hard. If the user chooses the easy level, they get 10 attempts, if they choose the hard level, they get 5 attempts.
As I was writing the code, I could see how much I was repeating myself.
I try to think as much as possible about the DRY principle: Don’t Repeat Yourself. If we start writing down the same lines of code or copy pasting, it means there’s room for refactoring.
Refactoring is the process of restructuring code, while not changing its original functionality. The goal is to improve internal code by making small changes without altering the code's external behavior. It aims at making code cleaner, easier to read, maintain and fix.
For example, I’m repeating similar lines of code for checking if the level is 'easy' or 'hard', for printing the number of attempts remaining and I should combine the feedback for too high, too low or equal to the correct number into a single if-else
block.
Final code after refactoring: (removed 19 lines of code!)
2/ Blackjack
Here’s a concise explanation for this program:
It imports necessary modules for the game (random / os / logo).
It defines a function called
play_blackjack
, which is the main game loop.Inside the game loop, It initializes two lists to represent the player's and computer's hands, and a list of cards with their values.
It deals two cards to both the player and the computer.
It calculates the scores for both the player and the computer based on the cards in their hands.
It displays the initial game state.
If either the player or the computer gets a Blackjack (a score of 21 with 2 cards), it prints the winner.
If not, it allows the player to choose whether to get another card ('y') or pass ('n') and updates the player's score accordingly.
It then lets the computer draw cards until its score is at least 17.
After the computer's turn, it compares the scores and announces the winner or a tie.
It asks the player if they want to play again and clears the console if they choose to continue.
Thank you for reading! If you have any questions, feel free to reach out to me!
Happy coding!
Camille