Type Casting and None
15 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)Data from users or APIs often arrives as text. Type casting converts data into the correct type for calculations.
Converting strings to numbers
Type casting is converting a value from one type to another, for example text "42" to the number 42 with int(). The original object is not changed; a new one is returned.
Use int() to convert numeric text into an integer, and float() to convert into a decimal number.
text_count = "42"count = int(text_count)print(count + 8)Example 1 · int() cuts the decimal part
print(int(3.9))print(int(-3.9))3 -3
What this code does
int()drops the decimal part; it does not round.- For negative numbers it moves toward zero, so -3.9 becomes -3.
The console prints 50. Without int(), adding '42' + 8 raises a TypeError because Python does not perform implicit string-to-number coercion.
Handling conversion errors
ValueError is the error Python raises when a value has the right type but cannot be used, such as int("abc"). The program stops unless the error is handled.
Passing non-numeric text to int() raises a ValueError at runtime.
price_text = "99.50"price = float(price_text)print(price)Notice that int("99.50") fails with a ValueError because the string contains a decimal point. Convert to float first or parse cleanly.
Converting numbers to strings
Use str() to turn any integer, float or boolean into a printable string representation.
status_code = 200message = "HTTP " + str(status_code)print(message)Example 2 · Text from a form becomes a total
raw_input = "250"quantity = int(raw_input)unit_price = 14.5total = quantity * unit_price
print(total)print(type(total))print(str(total) + " USD")3625.0 <class 'float'> 3625.0 USD
What this code does
raw_inputis converted from string to integer.totalmultiplies integer by float, resulting in a float (3625.0).str(total)converts the number back to text for string concatenation.
The console displays HTTP 200. Joining strings with the + operator requires all parts to be strings.
The None singleton
None is the single value that means no value. Its type is NoneType. Use it for "nothing here yet", and test for it with the is operator.
Python uses None to represent the absence of a value or a null reference. Its type is NoneType.
cached_result = Noneprint(cached_result)print(cached_result is None)Example 3 · A value that is not there yet
middle_name = Noneprint(middle_name is None)print(type(middle_name))True <class 'NoneType'>
What this code does
middle_nameis bound toNone, the "no value" object.is Noneis the correct way to test for it.- Its type is
NoneType.
Always check for None using the identity operator is None, not equality == None.
Next step
Check your understanding
9 quick questions