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.

Tiny Practice: Convert Numeric Text

Convert "30" into an integer stored in minutes.

Starter template

minutes = CHANGE_ME
print(type(minutes))
Line-by-line explanation
  1. The first line needs a conversion.
  2. The second line checks the result.
Hint
  1. Use int.
  2. Put "30" inside its brackets.
  3. The expected type is int.
Show Solution
minutes = int("30")
print(type(minutes))
Line-by-line explanation
  1. int("30") creates integer 30.
  2. The integer is stored in minutes.
  3. The second line confirms int.