Type Conversion

type conversion

Type conversion

Video Transcript

In this section, we will learn about type conversion. We've already learned how to create different variable types in Python:
  • greeting = "hello" gives us a string
  • answer = 42 gives us an integer
  • distance = 4.2 gives us a float
But what if we what to change a variable's data type? Say, for example, we had a string "145", but we wanted to use it to do some math. As it is now, Python won't let you do any math. If we try, we get:
var = "145"
result = var + 4
print(result)

# Traceback (most recent call last):
#   File "<stdin>", line 1, in <module>
# TypeError: can only concatenate str (not "int") to str
In order to make this work, we first have to convert "145" to an integer. We can do this using the built-in data type keywords:
  • str() for string
  • int() for integer
  • float() for float
Let's try our example again:
var = int("145")
result = var + 4
print(result)
# 149
This is especially useful for converting input from the user from strings to numbers:
radius = float(input("Enter a radius: "))
area = 3.14 * radius ** 2
print(f"The area of a circle with radius {radius} is {area}.")
Be careful when converting though! If your string can't be turned into a number, because it's something like "hello" for example, your program will give you an error!
Last section Next section