Variables & Data Types

Type Conversion

Sometimes you need to convert one data type to another.

Common Conversions

# String to Integer
age = int("25")      # 25

# String to Float
price = float("19.99")  # 19.99

# Number to String
text = str(100)      # "100"

# To Boolean
bool(1)    # True
bool(0)    # False
bool("")   # False
bool("hi") # True

Checking Types

Use

type()
to see what type a value is:

print(type(25))      # <class 'int'>
print(type("Hello")) # <class 'str'>
print(type(3.14))    # <class 'float'>

Why It Matters

# This causes an error:
age = input("Enter age: ")  # Returns a string!
new_age = age + 1  # Error! Can't add string + int

# Fix with conversion:
age = int(input("Enter age: "))
new_age = age + 1  # Works!
Visualizer
$ python convert.py
String: 42, Type: <class 'str'> Integer: 42, Type: <class 'int'> After adding 10: 52

Interactive Visualization

python
Loading...
Output
Run execution to see output...