Specify a Variable Type
Sometimes you need a variable to have a particular type, and casting is how you get it. Python is object-oriented, so classes define its data types, even the primitive ones.
That means casting comes down to calling constructor functions:
int()- makes an integer from an integer literal, from a float literal (dropping everything after the decimal point), or from a string literal, as long as the string holds a whole numberfloat()- makes a float from an integer or float literal, and also from a string literal, as long as the string holds an integer or a floatstr()- makes a string from many data types, such as float literals, integer literals, and strings
Example
Integers:
Prompt
Write a Python program that uses the int() constructor to create integers from an integer literal, a float literal, and a string literal.
Output: complete Python program
main.py
x = int(1) # x will be 1
y = int(2.8) # y will be 2
z = int("3") # z will be 3
Example
Floats:
Prompt
Write a Python program that uses the float() constructor to create floats from an integer, a float, and string literals.
Output: complete Python program
main.py
x = float(1) # x will be 1.0
y = float(2.8) # y will be 2.8
z = float("3") # z will be 3.0
w = float("4.2") # w will be 4.2
Example
Strings:
Prompt
Write a Python program that uses the str() constructor to create strings from a string, an integer, and a float.
Output: complete Python program
main.py
x = str("s1") # x will be 's1'
y = str(2) # y will be '2'
z = str(3.0) # z will be '3.0'