In int type conversion, we use the int() function to convert variables of other types to int type. Variable can be of any type such as float, string, bool.
While performing int type conversion, we need to remember the following points.
- When converting string type to int type, a sting must contain integral value only and should be base-10.
- We can convert any type to int type, but we cannot perform complex to int type.
Casting float value to an integer
pi = 3.14 # float number
print(type(pi)) # Output class 'int'
# converting float integer
num = int(pi)
print("Integer Number:", num) # Output 3
print(type(num)) # Output class 'int'
Casting Boolean value to an integer
flag_true = True
flat_false = False
print(type(flag_true)) # Output class 'bool'
# converting boolean to integer
num1 = int(flat_true)
num2 = int(flat_false)
print("Integer numer1:", num1) # Output 1
print(type(num1)) # Output class 'int'
print("Integer number2:", num2) Output 0
print(type(num2)) # Output class 'int'
Casting a string to an integer
string_num = "255"
print(type(string_num)) # Output class 'str'
# converting str to integer
num1 = int(string_num)
print("Integer numer1:", num1) # Output 255
print(type(num1)) # Output class 'int'
When converting string type to int type, a sting must contain integral value only and should be base-10. If you try to convert.
Example:
string_num = "Score is 95"
print(type(string_num)) # Output class 'str'
# ValueError: invalid interal for int() with base 10: 'Score is 95'
num = int(string_num)
print(num)
Float type conversion
In float type conversion we use a built-in function float(). This function converts variables of other types to float types.
Casting integer to float
num = 25
print(type(num)) # Output class 'int'
# converting float to integer
num1 = float(num)
print("Float number:", num1) # Output 25.0
print(type(num1)) # Output class 'float'
Casting Boolean to float
flag_true = True
flag_false = False
print(type(flag_true)) # Output class 'bool'
# converting boolean to float
num1 = float(flag_true)
num2 = float(flat_false)
print("Float number 1:", num1) # Output 1.0
print(type(num1)) # class 'float'
print("Float number 2:". num2) # Output 0.0
print(type(num2)) # class 'float'
Casting string to float
string_num = "10.58"
print(type(string_num)) # Output class 'str'
# converting str to float
num1 = float(string_num)
print("Float number:", num1) # Output 10.58
print(type(num1)) # class 'float'
While performing float type conversion, we need to remember some points.
- We can convert any type to float type, but we cannot cast complex to float type.
- While converting string type to float type, a string must contain an integer or decimal value of base-10.