Skip to content
PythonVariables and Basic Databeginner21 min read

Type Conversion

Convert values between strings, integers, floats, and booleans while understanding conversion rules, numeric promotion, and common errors.

In this lesson, you will learn

  • ✓Use int(), float(), str(), and bool() to perform explicit type conversion.
  • ✓Distinguish ValueError from TypeError during conversion.
  • ✓Explain why converting a float to an integer truncates toward zero.
  • ✓Predict Boolean conversions using Python truth-value rules.
  • ✓Distinguish explicit conversion from implicit numeric promotion.
  • ✓Represent integers in binary, octal, and hexadecimal, and parse integers written in a specified base.

1. Convert to an integer with int()

The int() function returns an integer from a compatible value. For example, int("22") converts the string "22" into the integer 22. This is useful when a number is received as text, such as input from a user.

When int() receives a float, it discards the fractional part by truncating toward zero. It does not round to the nearest integer: int(3.9) returns 3, and int(-3.9) returns -3.

A string containing a decimal point, such as "3.9", cannot be converted directly with int(). The call int("3.9") raises ValueError. If the decimal value is intended, convert it to float first. Also remember that int() can accept integers written in a specified base through its second argument, as explained later in this lesson.

Convert an integer string

Convert an integer string
python
age_text = "22"
age = int(age_text)
print(age)
print(type(age))
Output
22 <class 'int'>

age_text refers to a string containing the characters 2 and 2. int(age_text) creates the integer value 22. type(age) confirms that the resulting value is an int, not a str.

Caution

Do not use int() when you need rounding. For example, int(3.9) returns 3, whereas round(3.9) returns 4. Python’s round() also uses ties-to-even for exact halfway cases, such as round(2.5) returning 2 and round(3.5) returning 4.

2. Convert to a floating-point number with float()

The float() function converts compatible numeric values and numeric strings into floating-point numbers. For example, float("8") returns 8.0, and float("2.75") returns 2.75.

A float can represent fractional values, but it uses finite-precision binary floating-point arithmetic. Consequently, some decimal fractions cannot be represented exactly. For example, calculations involving 0.1 and 0.2 may produce a result whose displayed representation is not exactly 0.3.

If a string does not contain a valid floating-point representation, float() raises ValueError. The function also accepts certain textual representations such as "inf" and "nan", so a successful conversion does not always mean the result is a finite number.

Convert numeric text

Convert numeric text
python
whole = float("8")
fraction = float("2.75")
print(whole)
print(fraction)
print(type(whole))
Output
8.0 2.75 <class 'float'>

Both strings represent values that float() can interpret. The integer-looking string "8" becomes the float 8.0. type(whole) confirms that the result is a float.

Caution

float() does not guarantee exact decimal arithmetic. For applications that require exact decimal representations, such as many financial calculations, consider Python’s decimal.Decimal type.

3. Convert a value to a string with str()

The str() function produces a string representation of a value. It is useful when building messages, formatting information, or converting a number into text.

After a number is converted to a string, it is no longer a numeric value. For example, "12" + "3" produces the string "123", while 12 + 3 produces the integer 15.

You do not always need str() when displaying a value. print() accepts multiple arguments, so print("Age:", age) can display a label and an integer without explicitly converting the integer to a string.

Build a message using str()

Build a message using str()
python
age = 22
message = "Age: " + str(age)
print(message)
print(type(message))
Output
Age: 22 <class 'str'>

age stores the integer 22. str(age) produces the string "22". The + operator joins the two strings into "Age: 22". The final message is a string.

Caution

Use conversion intentionally. Converting a number to text is appropriate for messages, but convert valid numeric text to int or float before performing arithmetic.

4. Convert to a Boolean with bool()

The bool() function returns either True or False according to Python’s truth-value rules. These rules are also used by conditions such as if and while.

Common falsy values include False, None, numeric zero, and empty strings or collections. Examples include 0, 0.0, "", [], (), {}, and set().

Most other values are truthy. In particular, the strings "False" and "0" are both truthy because they are non-empty strings. bool() checks whether a value is truthy; it does not interpret the meaning of words written inside a string.

If a program receives a textual answer such as "yes" or "no", compare the text explicitly or validate it against the allowed answers instead of relying on bool(text).

Truthy and falsy values

Truthy and falsy values
python
print(bool(0))
print(bool(5))
print(bool(""))
print(bool("False"))
print(bool([]))
print(bool(None))
Output
False True False True False False

The integer 0 is falsy, while the nonzero integer 5 is truthy. An empty string is falsy. The string "False" contains characters and is therefore truthy. An empty list and None are also falsy.

Caution

Never assume that bool("False") returns False. For text-based yes/no input, normalize and validate the answer, for example by using answer.strip().lower() and comparing it with accepted strings.

5. Understand conversion errors

A conversion may fail when the supplied value cannot be interpreted as the requested type. Two common exceptions are ValueError and TypeError.

ValueError commonly means that the object has an acceptable type for the operation, but its value is unsuitable. For example, int("hello") raises ValueError because the string is not a valid integer representation.

TypeError commonly means that the supplied object type is not supported for the operation. For example, int(None) raises TypeError.

When converting user input, handle the errors that are reasonably expected. Catching a specific exception makes the program’s behavior clearer and avoids hiding unrelated programming errors.

Handle invalid integer input

Handle invalid integer input
python
text = "twelve"
try:
number = int(text)
except ValueError:
print("Not a valid integer")
Output
Not a valid integer

int("twelve") raises ValueError because the text is not a valid integer representation. Python transfers control to the matching except block. The program prints a useful message instead of terminating with an unhandled exception.

Caution

The second example’s output depends on user input. If the user enters "hello", the program prints the validation message instead. Do not catch every exception indiscriminately when only invalid numeric text is expected.

6. Understand implicit numeric conversion

Explicit conversion occurs when the programmer calls a conversion function such as int() or float(). Implicit conversion occurs when Python applies a type rule automatically during an operation.

For example, adding an int to a float produces a float result. In the expression 3 + 2.5, the integer participates in the mixed numeric operation as a floating-point value, and the result is 5.5.

This behavior does not mean Python automatically parses arbitrary strings into numbers. The expression 5 + "2" raises TypeError. Convert the string first if numeric addition is intended.

Integer plus float

Integer plus float
python
result = 3 + 2.5
print(result)
print(type(result))
Output
5.5 <class 'float'>

3 is an int and 2.5 is a float. Python supports this mixed numeric operation and produces a floating-point result. The resulting value is 5.5 and its type is float.

Caution

Python does not automatically convert "5" to 5 in an arithmetic expression. The expression 5 + "2" raises TypeError, whereas int("5") + 2 returns 7.

7. Convert integers to binary, octal, and hexadecimal

Python provides bin(), oct(), and hex() to obtain string representations of integers in binary, octal, and hexadecimal notation, respectively.

These functions return strings with prefixes: bin() uses 0b, oct() uses 0o, and hex() uses 0x. They change how the integer is represented as text, not the underlying integer value.

To convert a string written in a particular base into an integer, use int(text, base). For example, int("101", 2) interprets the text as a binary number and returns the decimal integer 5.

The base supplied to int() must be within the supported range of 2 through 36, or be 0 when Python should infer a base from a recognized prefix. When a base is specified explicitly, the text must be valid for that base.

Display integers in different bases

Display integers in different bases
python
print(bin(10))
print(oct(10))
print(hex(10))
print(int("101", 2))
Output
0b1010 0o12 0xa 5

The decimal integer 10 is represented as 1010 in binary. The same integer is represented as 12 in octal and a in hexadecimal. The prefixes identify the bases of the returned strings. int("101", 2) parses the binary text 101 and returns the integer 5.

Caution

bin(10) returns the string "0b1010"; it does not turn the integer 10 into a different numeric value. Use int(text, base) when you need to parse a number written in another base.

8. Dry run: converting input before calculating

A dry run follows each statement and records the value and type of each variable. This helps you identify when a value is still text and when it has become a number.

Trace a price and quantity calculation

Trace a price and quantity calculation
python
price_text = "12.5"
quantity_text = "4"
price = float(price_text)
quantity = int(quantity_text)
total = price * quantity
print(total)
print(type(total))
Output
50.0 <class 'float'>

Step 1: price_text stores the string "12.5". Step 2: quantity_text stores the string "4". Step 3: float(price_text) produces 12.5, a float. Step 4: int(quantity_text) produces 4, an int. Step 5: 12.5 * 4 produces 50.0, a float. Step 6: print(total) displays 50.0, and type(total) confirms that the result is a float.

Common pitfalls to avoid

Real debugging lessons and exact syntax contrasts to avoid runtime bugs

#1 Expecting int(3.9) to round to 4.

Why it happens: int() truncates the fractional part toward zero; rounding is a separate operation.

Incorrect Approach
script.py
python
Expecting int(3.9) to round to 4.
Correct Solution
script.py
python
int() truncates toward zero. int(3.9) is 3 and int(-3.9) is -3. Use round() when rounding is intended.

Key takeaway: int() truncates toward zero. int(3.9) is 3 and int(-3.9) is -3. Use round() when rounding is intended.

#2 Expecting int("3.9") to work.

Why it happens: The text "3.9" contains a decimal point, so it is not a valid integer literal for int(); convert it with float() first if appropriate.

Incorrect Approach
script.py
python
Expecting int("3.9") to work.
Correct Solution
script.py
python
The string contains a decimal point, so int("3.9") raises ValueError. Use float("3.9") if a float is intended.

Key takeaway: 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.

Why it happens: A non-empty string is truthy regardless of its contents, so the string "False" evaluates to True in a Boolean context.

Incorrect Approach
script.py
python
Assuming bool("False") is False.
Correct Solution
script.py
python
Any non-empty string is truthy, including "False" and "0". Parse textual yes/no answers explicitly.

Key takeaway: Any non-empty string is truthy, including "False" and "0". Parse textual yes/no answers explicitly.

#4 Assuming Python automatically converts numeric strings in arithmetic.

Why it happens: Python does not generally convert numeric strings to numbers automatically for arithmetic; convert the text explicitly.

Incorrect Approach
script.py
python
Assuming Python automatically converts numeric strings in arithmetic.
Correct Solution
script.py
python
Convert numeric text explicitly with int() or float() before performing numeric calculations.

Key takeaway: Convert numeric text explicitly with int() or float() before performing numeric calculations.

#5 Confusing ValueError with TypeError.

Why it happens: ValueError usually means a value has the right general type but invalid content for the conversion, while TypeError indicates an operation received an inappropriate type.

Incorrect Approach
script.py
python
Confusing ValueError with TypeError.
Correct Solution
script.py
python
ValueError often indicates an unsuitable value, as in int("hello"). TypeError can indicate an unsupported object type, as in int(None).

Key takeaway: ValueError often indicates an unsuitable value, as in int("hello"). TypeError can indicate an unsupported object type, as in int(None).

#6 Assuming float values always represent decimal fractions exactly.

Why it happens: Binary floating-point has finite precision, so some decimal fractions cannot be represented exactly.

Incorrect Approach
script.py
python
Assuming float values always represent decimal fractions exactly.
Correct Solution
script.py
python
Binary floating-point cannot represent every decimal fraction exactly. Consider decimal.Decimal when exact decimal arithmetic is required.

Key takeaway: Binary floating-point cannot represent every decimal fraction exactly. Consider decimal.Decimal when exact decimal arithmetic is required.

Ready for hands-on challenges?

Test your skills with shuffled coding challenges in the Practice Arena.

Practice Arena →

Technical and placement interview questions

Frequently tested interview questions with detailed, full answers (click to expand)

Q1:What is type conversion in Python?
Answer:
Type conversion obtains a value of one type from a value of another type. Explicit conversion uses functions such as int(), float(), str(), and bool(). Python also applies certain automatic numeric promotion rules during operations.
Q2:What is the difference between int(3.9) and round(3.9)?
Answer:
int(3.9) truncates toward zero and returns 3. round(3.9) returns 4 because 3.9 is closer to 4 than to 3. Python uses ties-to-even for exact halfway cases.
Q3:What is the difference between int("3.9") and int(float("3.9"))?
Answer:
int("3.9") raises ValueError because the text is not a valid integer representation. float("3.9") first produces 3.9, and int(3.9) then truncates it to 3.
Q4:What is the difference between ValueError and TypeError in conversion?
Answer:
ValueError commonly indicates that the supplied value cannot be interpreted as requested, as in int("hello"). TypeError commonly indicates that the object type is unsupported for the operation, as in int(None).
Q5:Why is bool("False") equal to True?
Answer:
Python treats non-empty strings as truthy. bool() checks the truth value of the string object, not whether the characters spell the word "False".
Q6:What is the difference between explicit and implicit conversion?
Answer:
Explicit conversion is requested directly by the programmer, such as int("5"). Implicit numeric promotion occurs automatically in supported operations, such as 3 + 2.5 producing the float 5.5.
Q7:Why does "5" + 2 raise TypeError?
Answer:
The operands have incompatible types for addition: one is a string and the other is an integer. Convert the string explicitly with int("5") + 2 if numeric addition is intended.
Q8:What do bin(), oct(), and hex() do?
Answer:
They return string representations of an integer in binary, octal, and hexadecimal notation. Their results include the prefixes 0b, 0o, and 0x, respectively.
Q9:How can Python parse an integer written in another base?
Answer:
Use int(text, base). For example, int("101", 2) returns 5 because binary 101 equals decimal 5.
Q10:Why should conversion errors be handled carefully?
Answer:
User input may contain invalid numeric text. Catching an expected exception such as ValueError lets a program respond with a useful message. Catching overly broad exceptions or silently substituting arbitrary values can hide programming errors and invalid data.

Key takeaways

  • Use int(), float(), str(), and bool() for explicit type conversion.
  • int() truncates floats toward zero rather than rounding.
  • float() accepts compatible numeric strings but uses finite-precision binary floating-point.
  • str() produces text; + concatenates strings but adds numbers.
  • Non-empty strings are truthy, even when their text says "False" or "0".
  • ValueError and TypeError commonly indicate different kinds of conversion problems.
  • Python promotes some numeric operands automatically but does not automatically parse numeric strings.
  • bin(), oct(), and hex() return string representations; int(text, base) parses text written in a specified base.
Was this lesson helpful?
Found an error? Report an issue

Related Topics & Next Steps

4 Recommended Lessons

Strengthen your Python foundation with these complementary core lessons: