Type Conversion
Convert compatible values between strings, integers, floats, and booleans while avoiding common conversion errors.
- Use int(), float(), str(), and bool() for explicit conversion.
- Recognize conversions that raise ValueError or TypeError.
- Explain truncation toward zero when converting floats to integers.
- Understand truth-value testing with bool().
- Distinguish explicit conversion from implicit numeric promotion.
1. Convert to int with int()
int() can convert an integer-like value or a string containing a valid integer representation into an integer. When converting a float to int, Python truncates toward zero; it does not round to the nearest integer.
For strings, decimal points are not accepted by int() directly. int("3.5") raises ValueError, while int(3.5) returns 3.
Convert a valid integer string
age_text = "22"
age = int(age_text)
print(age)
print(type(age))The string "22" represents a valid integer. int() returns an integer object, which is bound to age.
Common Mistake to Avoid
Truncation toward zero
print(int(3.9))
print(int(-3.9))The fractional part is discarded. For negative numbers, truncation moves toward zero, so -3.9 becomes -3 rather than -4.
2. Convert to float with float()
float() converts compatible numeric values and numeric strings to floating-point values. A valid integer string such as "8" can become 8.0; a decimal string such as "2.75" can become 2.75. Invalid numeric text raises ValueError.
Convert numeric text
whole = float("8")
fraction = float("2.75")
print(whole)
print(fraction)Both string values are valid numeric representations. The results are float values, so the whole number is displayed with .0.
3. Convert to str with str()
str() creates a readable string representation of a value. It is useful when combining values into a message, although print() can also display multiple values without manually converting them.
Converting a value to a string does not preserve its original numeric type. After conversion, arithmetic operators such as + may perform string concatenation instead of numeric addition.
Build a message
age = 22
message = "Age: " + str(age)
print(message)age is an integer. str(age) produces the string "22". The + operator concatenates the two strings.
4. Convert to bool with bool()
bool(value) returns True or False according to the value’s truth value. Common false values include False, None, numeric zero, and empty collections or strings. Most other objects are true, including the string "0" and the string "False" because both strings are non-empty.
Truthiness is not the same as parsing a textual yes/no answer. bool("False") is True. If a program accepts words such as yes and no, compare or parse the text explicitly.
Truthy and falsy values
print(bool(0))
print(bool(5))
print(bool(""))
print(bool("False"))
print(bool([]))Zero, an empty string, and an empty list are false in a Boolean context. The string "False" is non-empty, so it is true.
5. Invalid conversions and errors
ValueError commonly occurs when the type is acceptable but the value cannot be interpreted as requested, such as int("hello"). TypeError can occur when a conversion function is given an object type it does not support, such as int(None).
When processing user input, catch the errors that are expected for the input format. Do not silently replace invalid data with an arbitrary number, because that can hide bugs.
Handle invalid numeric text
text = "twelve"
try:
number = int(text)
except ValueError:
print("Not a valid integer")int("twelve") raises ValueError. The except block handles that specific conversion problem and allows the program to continue.
6. Implicit numeric conversion
Python performs some conversions automatically during operations. For example, when an int and a float are added, the integer is promoted to a float for the calculation and the result is a float. This is a numeric operation rule, not a general promise that Python automatically converts arbitrary incompatible values.
Python does not automatically convert the string "5" to the integer 5 when adding it to an integer. Explicit conversion is needed for that.
Integer plus float
result = 3 + 2.5
print(result)
print(type(result))The int operand participates in the mixed numeric operation as a float. The resulting value is 5.5 and its type is float.
7. Convert integers to bases
The built-in functions bin(), oct(), and hex() return strings representing an integer in binary, octal, and hexadecimal notation. Their results include prefixes 0b, 0o, and 0x. These functions format an integer; they do not change the integer into a different numeric value.
To parse a string written in a specified base, use int(text, base), for example int("101", 2) returns the decimal integer 5.
Base representations
print(bin(10))
print(oct(10))
print(hex(10))
print(int("101", 2))10 is represented as 1010 in binary, 12 in octal, and a in hexadecimal. int("101", 2) interprets the text 101 as a base-2 number and returns integer 5.
Common Pitfalls & Mistakes to Avoid
#1 Expecting int(3.9) to round to 4.
Explanation: int() truncates toward zero; int(3.9) is 3 and int(-3.9) is -3.
#2 Expecting int("3.9") to work.
Explanation: The string contains a decimal point, so int("3.9") raises ValueError. Use float("3.9") if a float is intended.
#3 Assuming bool("False") is False.
Explanation: Any non-empty string is truthy, including "False" and "0".
#4 Assuming Python automatically converts numeric strings in arithmetic.
Explanation: Convert text explicitly with int() or float() before numeric calculations.
Practice Questions
Given price_text = "12.5" and quantity_text = "4", convert them to suitable numeric types, multiply them, and print the total.
Print bool(0), bool("0"), bool(""), and bool(None), each on its own line.
Type Conversion Knowledge Check
1. What does int(-3.9) return?
2. What is bool("False")?
3. Which exception does int("hello") raise?
Technical & Placement Interview Questions
Key Takeaways & Summary
- Use int(), float(), str(), and bool() for explicit conversions.
- int() truncates floats toward zero rather than rounding.
- Invalid conversions can raise ValueError or TypeError.
- Non-empty strings are truthy, even when their text says False.
- Python promotes some numeric operands automatically, but does not parse numeric strings automatically.
Finished reading this lesson?
Track your course progress and update your learning dashboard.
Related Topics & Next Steps
Strengthen your programming fundamentals with these related lessons: