Lesson 13 of 18 · 2 min
Type Conversion — Changing Between Types
The Analogy: Currency Exchange
When you travel from India to the USA, you convert rupees to dollars. The fundamental value is similar, but it is in a different form accepted by the new context. Type conversion works the same way — changing the form of data so Python can use it in a new context.
The Conversion Functions
| Function | Converts To | Example | Result | Warning |
|---|---|---|---|---|
int() | Whole number | int("42") | 42 | Truncates decimals, not round |
float() | Decimal number | float("3.14") | 3.14 | |
str() | Text | str(42) | "42" | |
bool() | True/False | bool(0) | False |
int() Examples
text_score = "95" # the text "95" — cannot do math yet score = int(text_score) # convert text to integer number print(score + 5) # now math works: 95 + 5 = 100 decimal = 3.99 # a decimal number whole = int(decimal) # TRUNCATES (chops off decimal) — does NOT round! print(whole) # displays 3, NOT 4 — the .99 is simply discarded
Output: 100 3
float() Examples
price_text = "99.99" # text that looks like a price
price = float(price_text) # convert to actual decimal number
tax = price * 0.18 # can now do math: apply 18% GST
print(f"Price after tax: {price + tax:.2f}") # display total with 2 decimals
Output: Price after tax: 117.99
What is Truthy and Falsy?
Every Python value can be evaluated as True or False:
print(bool(0)) # 0 is falsy (zero = nothing) → False
print(bool(1)) # any non-zero number is truthy → True
print(bool(-5)) # negative numbers are also truthy → True
print(bool("")) # empty string is falsy (nothing) → False
print(bool("hi")) # non-empty string is truthy → True
print(bool(None)) # None is falsy → False
Output: False True True False True False
