03 - Type Conversion
A simple picture
Imagine the text "25" written on a card. It looks like a number, but Python still treats it as text because it has quotation marks. Conversion is like moving the value from a “text” box into a “whole number” box.
Why conversion is needed
Sometimes a value has the wrong type for the job. In this example, both values are strings because they have quotation marks:
first_text = "2"
second_text = "3"
print(first_text + second_text) # 23 because strings are joined
Convert the strings into integers before arithmetic:
first_number = int(first_text)
second_number = int(second_text)
print(first_number + second_number) # 5
Common conversion functions
int()
print(int("25"))
print(int(4.9)) # 4: fractional part is discarded
int("4.9") fails because the text is not an integer literal. Convert through float() if decimal input is intentionally allowed.
float()
price = float("19.50")
print(price * 2)
str()
order_id = 105
message = "Order: " + str(order_id)
For formatted output, an f-string is usually clearer: f"Order: {order_id}".
bool()
Most values are truthy or falsy:
print(bool(0)) # False
print(bool(1)) # True
print(bool("")) # False
print(bool("False")) # True: non-empty text
print(bool([])) # False
Do not convert the string "False" to a boolean expecting False; it is non-empty text.
complex()
number = complex(3, 4)
print(number) # (3+4j)
This is useful for complex-number work, not ordinary price or age input.
Errors during conversion
int("ten") # ValueError
int("3.5") # ValueError
int(None) # TypeError
At this stage, read the error and correct the input. Later, exception handling will let you show a friendly message and ask again.
Important fact: conversion does not merely change a label. A successful conversion gives you a value of the requested type. Some information may be lost—for example,
int(4.9)gives4and discards the decimal part.
Converting several stored fields
quantity_text = "3"
price_text = "19.50"
quantity = int(quantity_text)
price = float(price_text)
print(quantity, type(quantity))
print(price, type(price))
Convert each field according to its meaning. Do not convert everything to float merely because the text contains digits.
Bug Hunter
Bug 1 — decimal text sent directly to int()
mark_text = "82.5"
mark = int(mark_text)
print(mark)
Bug 2 — the result was not saved
age_text = "10"
int(age_text)
print(type(age_text))
Conversion returns a value. It does not replace the original string automatically.
Bug 3 — surprising boolean text
answer = "False"
print(bool(answer))
Any non-empty string is truthy, even when its letters spell False.
Show Bug Hunter explanations
# Bug 1: allow decimal text first, then remove its decimal part if intended.
mark = int(float(mark_text))
# Bug 2: store the returned integer under a name.
age = int(age_text)
print(type(age))
# Bug 3: do not use bool(text) to understand yes/no words.
# Comparisons are taught in the next chapter. For now, remember that
# every non-empty string becomes True.
answer_value = False
print(answer_value)
Optional deeper look: does conversion change the original value?
No. Built-in conversion functions such as int(), float(), and str() return an object representing the converted value. The original object still exists while something refers to it. Store the returned value when you need it later.
Common mistakes
- Forgetting that quotation marks make a value a
str. - Calling
int()on decimal text. - Treating non-empty text such as
"no"as boolean false. - Converting before checking what format the user is allowed to enter.
Practice
Try these problems on this page. For each one, write the original type and the type you need after conversion.
Problems
- Convert the text age
"10"to an integer and print both types. - Convert the text price
"45.50"to a float and print both values. - Convert the integer
25to a string and join it with the text"Age: ". - Predict whether
int("40"),int("4.0"), andfloat("4.0")work, then run them separately. - Predict the result of
bool(0),bool(1),bool(""), andbool("False"). - Identify which of five conversion expressions will raise an error.
- Convert the decimal text
"82.7"to a float and then useint()to remove its decimal part. - Convert the values
0,1,"", and"hello"to booleans. - Write three examples that cause
ValueErrorwhen passed toint(). - Create a conversion plan for stored text values representing quantity, price, and discount.
Show hints
- Save the original and converted values under different names.
- Use
float()andtype(). - Use
str(25)before joining the text. - Run one conversion at a time because an error stops the program.
- Empty values are false; non-empty strings are true.
- Check both the argument type and its contents.
- Convert to
floatfirst and then toint. - Empty values and zero are false; non-empty text and non-zero numbers are true.
- Use words, decimal text, and empty text.
- Convert count to
int, money tofloat, and reject negative values.
Show solution ideas
- Use
age_text = "10",age = int(age_text), and twotype()calls. - Use
price_text = "45.50"andprice = float(price_text). - Use
message = "Age: " + str(25). int("40")andfloat("4.0")work;int("4.0")raisesValueError.- The results are
False,True,False, andTrue. int("12")works;int("12.5"),int("ten"), andint("")raiseValueError.whole_mark = int(float("82.7"))gives82; it does not round up.- Use
bool()on each value and compare the printed results. - Examples:
int("ten"),int("3.5"), andint(""). - Plan
intfor quantity andfloatfor price and discount; later chapters teach input validation.
Homework
Create a conversion notebook in code. Start with five stored values such as "12", "9.5", 0, True, and 25. Convert each value to one sensible new type and explain the result in a comment.
Checkpoint
Explain why "25" and 25 are different values. Then predict bool(0), bool(1), bool(""), and bool("False").