Skip to Content
Course content

12: Variables and Dynamic Typing

Click on the "Edit" button in the top corner of the screen to edit your slide content.

Wait, if I don't have to declare a type, how does Python actually know what's what?

Coming from other languages, it feels like you're missing something when you just write x = 10 instead of int x = 10. Here is the secret: in Python, the value has the type, not the variable name.

Think of the variable as just a name tag. When you write score = 100, Python creates an integer object (100) and then sticks the label "score" onto it. If you later write score = "Game Over", Python doesn't try to cram a string into an integer-shaped box. It simply peels the "score" label off the number 100 and sticks it onto a new string object.

# This is perfectly legal in Python
current_status = 42          # Now it's an int
current_status = "Active"    # Now it's a string
current_status = [1, 2, 3]   # Now it's a list

I'll be honest: this is incredibly liberating when you're prototyping, but it can bite you if you aren't paying attention to what your variables are actually holding at any given moment.

Are variables just "boxes" that hold data?

Most people describe variables as boxes, but that's actually a bit of a lie. In Python, variables are references (or pointers). They don't contain the data; they point to where the data lives in your computer's memory.

This becomes really important when you start working with things like lists. Look at this example:

player_one_inventory = ["Sword", "Shield"]
player_two_inventory = player_one_inventory

player_two_inventory.append("Potion")

print(player_one_inventory) 
# Output: ['Sword', 'Shield', 'Potion']

You might expect player_two_inventory to be a separate copy, but because you just pointed one label to the same list object, changing one "changes" the other. I've spent more hours than I care to admit debugging this exact behavior in my early career. Always remember: you're moving labels, not copying boxes.

Is it actually a good idea to change a variable's type mid-program?

Just because you can doesn't mean you should. While dynamic typing is a feature, "type-switching" a variable usually signals a design flaw. If a variable starts as an integer and ends up as a string, it's probably doing two different jobs.

The biggest risk is the TypeError. If you accidentally change a type and then try to perform an operation that doesn't make sense for that new type, Python will crash your program.

price = 19.99
# ... a lot of code happens ...
price = "Out of Stock" 

# This will crash because you can't multiply a string by a float
total = price * 1.05 

My advice? Keep your variables consistent. If you need to store a different type of data, just give it a new, descriptive name. Your future self—and anyone else reading your code—will thank you for it.




📋 Practical Task

The Inventory Reference Debugger

You are building a game where players can share a "Guild Stash" of items. However, there is a bug in the code: when a player adds an item to their personal inventory, it is accidentally appearing in the Guild Stash as well.

Your Task: Fix the provided code so that player_inventory is a separate object from guild_stash, ensuring that modifying the player's items does not affect the shared stash.

# BUGGY CODE
guild_stash = ["Health Potion", "Mana Potion", "Iron Key"]
player_inventory = guild_stash # This is the line causing the problem!

# The player finds a Rare Gem
player_inventory.append("Rare Gem")

print("Guild Stash:", guild_stash)
print("Player Inventory:", player_inventory)

# EXPECTED OUTPUT:
# Guild Stash: ['Health Potion', 'Mana Potion', 'Iron Key']
# Player Inventory: ['Health Potion', 'Mana Potion', 'Iron Key', 'Rare Gem']

Hint: You need to create a shallow copy of the list instead of just assigning the reference. Try using the .copy() method or slice notation [:].

Rating
0 0

There are no comments for now.

to be the first to leave a comment.