Menu

Casting, also called type conversion, is converting a value from one data type to another. You cast a value when it is the wrong type for the operation you need to perform: arithmetic needs numbers, joining text with + needs strings, a comparison such as greater than needs two values of the same type, and writing a line to a file needs text.

Conversion functions

Python 3 has a built-in function for each of the main data types, named after the type it produces. Each call returns a value of that type.

FunctionValue it returns
int()integer
float()real number
str()string
bool()Boolean

Two more functions work on single characters. ord() returns the integer character code (its ASCII value) of a character, and chr() turns a code back into a one-character string.

A conversion function returns a new value. It does not change the original variable unless you assign the result. For example, converting a text value to an integer gives a new integer; the original text variable still holds the text.

price_text = "12.50"
quantity_text = "3"
price = float(price_text)      # assign the new real number
quantity = int(quantity_text)
total = price * quantity
print("Total: " + str(total) + " pounds")

Output:

Total: 37.5 pounds

You can combine casting with other operations in one expression, provided the order is correct. The innermost call runs first, so wrapping input() in float() reads text and then converts it. Choose the target type to suit the job: integer or real for arithmetic, string for concatenation, Boolean for decisions, and a character code when you need to move between a character and its ASCII value.

The Programming Language Subset uses these same functions: convert data to the right type for the next step, such as turning text input into a real number before a calculation, or a number into a string when building an output line. Correct casting keeps a program robust, because mismatched types cause runtime errors that stop the program.

Practise this