Type Conversion

Let's say you have a string "145", and you try to do some math with it. You will get an error:
var = "145"
result = var + 4
print(result)

# Traceback (most recent call last):
#   File "main.py", line 2, in <module>
#     result = var + 4
# TypeError: can only concatenate str (not "int") to str
To make this work, first convert "145" to an integer. The are several functions for converting types:
  • str() - converts to string
  • int() - converts to integer
  • float() - converts to float
Let's retry the example above, but this time using the int() function:
var = int("145")
result = var + 4
print(result)
# 149
This is especially useful for converting user input 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}.")

Exercise 1 of 6

Write a line of code to convert a variable x to a string.

Your code

Exercise 2 of 6

Write a line of code to convert a variable x to an integer.

Your code

Exercise 3 of 6

Write a line of code to convert a variable x to a float.

Your code

Exercise 4 of 6

Fix the error in the code.
width = 15
length = input("Enter the length: ")
area = length * width
print(f"The area is {area}.")

Your code

Exercise 5 of 6

Fix the error in the code.
age = input("How old are you? ")
future_age = age + 20
print(f"In 20 years, you will be {future_age} years old.")

Your code

Exercise 6 of 6

Fix the error in the code.
result = "21" / 7
print(result)

Your code