Python · Stage 1 · Storing Information · Lesson 13 of 50

Converting Between Types

Create a new integer, float, or string from a compatible existing value.

int(), float(), and str() are built-in conversion functions. Each creates a new value.

age = int("12")
Line-by-line explanation
  1. "12" begins as a string.
  2. int("12") creates the integer 12.
  3. age = stores the new integer.
distance = float("2.5")
Line-by-line explanation
  1. "2.5" begins as text.
  2. float("2.5") creates the decimal number 2.5.
  3. The float is stored in distance.
score_text = str(100)
Line-by-line explanation
  1. 100 begins as an integer.
  2. str(100) creates the string "100".
  3. The string is stored in score_text.

Conversion works only when the value makes sense. Python cannot turn "twelve" into an integer because those letters are not digits.