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".
Adapted from Introduction to Python Programming by OpenStax (openstax.org), licensed under CC BY-NC-SA 4.0. Changes were made. License: CC-BY-NC-SA-4.0.
These eBooks are a prerelease and are not yet certified conformant with WCAG 2.1 AA or any other accessibility standard. Every page is built against an automated accessibility gate, and our target for the published editions is WCAG 2.2 Level AA. If something is unusable, please tell us.