Definition

Converting a value from one data type to another using a casting function.

Characteristics

  • Changes the data type of a value (e.g., integer to float, Boolean to string)
  • Common Python functions include:
    • int()
    • float()
    • str()
    • bool()

Examples

Conversion table

ConversionExampleResult
integer to floatfloat(5)5.0
float to integerint(3.14)3
integer to stringstr(5)"5"
string to floatfloat("2.1")2.1
Boolean to stringstr(True)"True"
integer to Booleanbool(0)False
integer to Booleanbool(1)True
string to Booleanbool("hello")True
string to Booleanbool("")False

Casting to Boolean

In Python, casting a string to a Boolean returns True if the string is non-empty, regardless of its contents. Only the empty string ("") casts to False.

Unintuitively, this means that bool("False") actually returns True.

Non-examples

Declare a variable

In languages where variables are declared, declaring a variable establishes its data type but does not change its data type—before declaration, there is no data type to change.

Initialise a variable

Initialising a variable a value does not change its data type—before initialisation, there is no data type to change.

Assign a variable a new value

In dynamically typed languages like Python, the data type of a variable can change. This means it is possible for a variable to have an initial value of one data type and for this value to be overwritten with a new value of a different data type. Manually overwriting a value—even if you change the data type—is not casting as casting requires the use of a casting function.

This is not an example of casting:

x = 5
x = 5.0

OCR J277

OCR H446