Casting

It is often necessary to change data from one type to another type. Just as you can convert a sandwich from solid to liquid form by using a blender, you can change data from one type to another type using a typecast function. You write the name of the desired new type in the same way as a function call, for example

x = float("3.4")
print(x-1)

changes the string "3.4" to the float 3.4, and then prints out 2.4. Without the typecast, the program would crash, since it cannot subtract a number from a string.

Various typecasts behave differently:

  • converting a float to an int loses the information after the decimal point, e.g. int(1.234) gives 1, and int(-34.7) gives -34.
  • converting a str to an int causes an error if the string is not formatted exactly like an integer, e.g. int("1.234") causes an error.
  • converting a str to a float causes an error if the string is not a number, e.g. float("sandwich") causes an error.

A common use of typecasting that we will see soon is to convert user input, which is always a string, to numerical form. Here is a quick illustration.

PRIMM – School Desks