Python Introduction | Basics of Values and Calculations | Type Conversion

Type Conversion and Text

Values have types. You cannot directly calculate with incompatible types, such as text and numbers. Python provides functions that convert a value to another type.

  • int(value) converts a value to an integer.
  • float(value) converts a value to a floating-point number.
  • str(value) converts a value to text.
  • bool(value) converts a value to a Boolean value.

Converting a value from one type to another is called type conversion or casting.

Combining Values with Text

Type conversion is useful when matching types for calculations and when displaying values as part of text. print can display any value, but concatenating text with a value of another type causes an error.

a = 123
b = 456
c = a + b
print(c)

Output:

579

The following code causes an error because it tries to concatenate text and an integer.

a = 123
b = 456
c = a + b
print('answer : ' + c)

Output:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can only concatenate str (not "int") to str

Convert c to text with str(c).

a = 123
b = 456
c = a + b
print('answer : ' + str(c))

Output:

answer : 579

Attempting to concatenate text and another type is a common beginner mistake. When print code fails, check whether a type conversion is needed.