Convert a literal of one data type to another data type.
Types:
- Implicit: Automatically converts object of one type into other.
- Explicit: Python's built-in functions int(), float() and str() to perform the explicit conversions such as string to integer.
Python doesn't allow automatic type conversion between unrelated data types.
- A string cannot be converted to any number type. However, an integer can be cast into a float.
- String and tuples can be converted into a list using
list()
- String and list can be converted to tuples using
tuple()
import os
print('Hello '+os.getlogin() + '! Executing python script')
print("\n")
# Implicit type casting
Int_value = 10
Boolean_value = True
# Note that True is equal to 1, and False is equal to 0.
print("Implicit type casting - sum of: ",Int_value," & ",Boolean_value,": ",Int_value+Boolean_value)
# Python built-in int() function converts an integer literal to an integer object, a float to integer, and a string to integer if the string itself has a valid integer literal representation.
print("----------------Int() function----------------------")