Back to: Python Programming
Type Casting is the process of converting a value of one data type to another. Used to convert user input from string to integer, rounding a float to an integer, changing an integer to a string, and so on. If we create a variable for the four main data types, we can print what each of the data types is:
name = ("Bob") # <-- STRING
age = 16 # <-- INTEGER
distance = 4.5 # <-- FLOAT
student = True # <-- BOOLEAN
print(type(name))
print(type(age))
print(type(distance))
print(type(student))
Outputs:
<class 'str'>
<class 'int'>
<class 'float'>
<class 'bool'>
To convert ‘age’ to a ‘float’:
name = ("Bob") # <-- STRING
age = 16 # <-- INTEGER
distance = 4.5 # <-- FLOAT
student = True # <-- BOOLEAN
age = float(age)
print(age)
Outputs ‘age’ with a decimal having converted it to a float:
16.0
To convert a ‘float’ to an ‘integer’, the decimal portion will be cut off (truncated).
name = ("Bob") # <-- STRING
age = 16 # <-- INTEGER
distance = 4.5 # <-- FLOAT
student = True # <-- BOOLEAN
distance = int(distance)
print(distance)
print(type(distance))
Output:
4
<class 'int'>
Converting a ‘float’ or an ‘integer’ to a ‘Boolean’ will set it to True for ALL values other than zero. Converting a ‘string’ to a ‘Boolean’ will be always be True unless the value is blank. This can be useful to validate all fields in a form have been filled and none left blank.
name = ("Bob") # <-- STRING
name_valid = bool(name)
print(name_valid)
Output:
True
If the name is left blank:
name = ("") # <-- STRING
name_valid = bool(name)
print(name_valid)
Output:
False
Above are examples of Explicit typecasting. We manually change the data type of each variable.
Implicit typecasting is automatic – if we divide two variables, a ‘float’ and an ‘integer’, the integer will automatically be converted to a float.
x = 4
y = 2.0
z = x / y
print (z)
Output:
2.0
Exercise:
Write some code asking for the users age and then output a sentence detail how many years it will be before they can legally vote or consume alcohol in Australia.