Switch Between Types
The problem...
You have a number. But you need text.
You have text. But you need a number.
You have a float. But you need an int.
Types don't always match what you need. And Python won't convert them for you automatically.
The idea!
Python gives you built-in functions to convert values from one type to another.
You decide what type you need. Python does the conversion.
Making it real
You've already seen this — every time you used input().
age = input("Enter your age: ")
print(type(age)) # <class 'str'> — always a string
age = int(age)
print(type(age)) # <class 'int'> — now a number
That's type conversion. One function. One line. Done.
The conversion functions
int()— converts to integerfloat()— converts to floatstr()— converts to stringbool()— converts to bool
In practice
# str to int
age = int("25")
print(age) # 25
print(type(age)) # <class 'int'>
# str to float
height = float("1.75")
print(height) # 1.75
# int to str
score = str(100)
print(score) # "100"
print(type(score)) # <class 'str'>
# int to float
price = float(5)
print(price) # 5.0
# float to int — truncates
result = int(3.9)
print(result) # 3 — not 4
Going further — bool()
Almost everything converts to True. Very few things convert to False.
print(bool(1)) # True
print(bool(0)) # False
print(bool("Bull")) # True
print(bool("")) # False — empty string
print(bool(3.14)) # True
print(bool(0.0)) # False
The rule: empty, zero, and nothing convert to False. Everything else is True.
What's really happening
Python doesn't guess. When you mix types, it throws an error.
Type conversion is you telling Python explicitly: "treat this value as this type."
Heads up!
int("25")works —int("Bull")throws a ValueErrorint(3.9)truncates — useround()if you need roundingbool(0)isFalse— useful to know, you'll see this in Control Flow- Always convert
input()before doing math
The mindset shift
Stop thinking: "Python should figure out the type."
Start thinking: "I know what type I need. I convert explicitly."
What you should understand now
int(),float(),str(),bool()convert between types- You can only convert compatible values —
int("Bull")fails - Empty and zero values convert to
False— everything else toTrue - Always convert
input()before doing math