Login
📚 Introduction to Python Programming
Chapters ▾
⇩ Download ▾

2.2 Type conversion

Learning objectives

By the end of this section you should be able to

  • Explain how the interpreter uses implicit type conversion.
  • Use explicit type conversion with int, float, and str.

Implicit type conversion

Common operations update a variable such that the variable's data type needs to be changed. Ex: A GPS first assigns distance with 250, an integer. After a wrong turn, the GPS assigns distance with 252.5, a float. The Python interpreter uses implicit type conversion to automatically convert one data type to another. Once distance is assigned with 252.5, the interpreter will convert distance from an integer to a float without the programmer needing to specify the conversion.

Explicit type conversion

A programmer often needs to change data types to perform an operation. Ex: A program should read in two values using input and sum the values. Remember input reads in values as strings. A programmer can use explicit type conversion to convert one data type to another.

  • int converts a data type to an integer. Any fractional part is removed. Ex: int(5.9) produces 5.
  • float converts a data type to a float. Ex: float(2) produces 2.0.
  • str converts a data type to a string. Ex: str(3.14) produces "3.14".