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
| Conversion | Example | Result |
|---|---|---|
| integer to float | float(5) | 5.0 |
| float to integer | int(3.14) | 3 |
| integer to string | str(5) | "5" |
| string to float | float("2.1") | 2.1 |
| Boolean to string | str(True) | "True" |
| integer to Boolean | bool(0) | False |
| integer to Boolean | bool(1) | True |
| string to Boolean | bool("hello") | True |
| string to Boolean | bool("") | False |
Casting to Boolean
In Python, casting a string to a Boolean returns
Trueif the string is non-empty, regardless of its contents. Only the empty string ("") casts toFalse.Unintuitively, this means that
bool("False")actually returnsTrue.
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