🤖

Nimbrights

Python Programming Tutorial - text-based game

Level 2: Casting & Identity

In this chapter, we focus on Transforming Data and Revealing the Essence of objects. As you build your adventure, you will often need to change data from one form to another to make your game logic work correctly.

Push through the uncertainty as we introduce these "Diagnostic Spells." Understanding how Python identifies and converts types is a fundamental skill for every Robot Wrangler.

1. Type Conversion (Casting)

The Concept: Sometimes you receive data as a String (like from an input() prompt) but need it to be a number to do math. We use int(), float(), and str() to convert them.

# User input is ALWAYS a string
gold_found = input("How many gold coins did you find in the dirt? ") 

# Convert string to integer to do math
gold_total = 100 + int(gold_found)

# Convert a float to a string to display it in a sentence
weight = 15.5
print("Your pack weighs " + str(weight) + " pounds.")
You won't use type() in your code destined for a user. But it is a useful tool for you to determine what type of variable you are interacting with. So use it when you are testing your adventure.

2. Booleans (bool)

The Concept: A Boolean represents a truth value: either True or False. These act as switches for your adventure logic.

# Setting Boolean states
is_gate_locked = True
has_magic_key = False

print(f"Is the path blocked? {is_gate_locked}")

# You find a key!
has_magic_key = True
print("You picked up the key. Can you open the door now?")
print(has_magic_key)

3. The Identify Spell: type()

The Concept: In the heat of battle, you might forget what kind of data a variable holds. The type() function reveals its "essence."

# Let's inspect different items in the game world
item_name = "Excalibur"
damage = 50
crit_chance = 0.15
inventory = ["Map", "Potion"]
stats = {"STR": 18, "DEX": 12}
is_alive = True

print(type(item_name))  # Output: <class 'str'>
print(type(damage))     # Output: <class 'int'>
print(type(crit_chance))# Output: <class 'float'>
print(type(inventory))  # Output: <class 'list'>
print(type(stats))      # Output: <class 'dict'>
print(type(is_alive))   # Output: <class 'bool'>
This would be good information to put into a debugging log. You'll learn how to do this later.