Last updated on February 20, 2023
Every value has a specific data type, when we change the data type of value from one to another is called type casting.
In python, type casting breaks down into two types,
In this type, python sets data type after analyzing data. It means every value has a data type that sets python automatically. Let’s understand it by an example, declare a variable and assign a value to it.
favoriteColor = ‘green’
Python sets the string data type to the favoriteColor
variable because python reads the assigned value from favoriteColor
variable, it will find alphabet letters.
Below are variables along with values where python sets data type automatically.
age = 27
print(type(age))
# Output: <class 'int'>
Python sets integer data type to age variable because it finds numeric letters. The type()
function returns <class 'int'>
in the terminal that proves python has set the integer data type to the age variable.
price = 13.50
print(type(price))
# Output: <class 'float'>
The price variable assigned value has a decimal point that makes it a decimal number. When python finds a decimal point between the numbers then it sets the float data type to it. That’s why type()
function returns <class 'float'>
in the terminal.
color = "red"
print(type(color))
# Output: <class 'str'>
In the color variable, the value consists of alphabet letters. It’s making them string data types. So when python finds alphabet letters then it sets the string data type. That’s why the type()
function returns <class 'str'>
in the terminal.
In this type, the user sets the data type as per requirements. Suppose, if the user gets numeric values with a string data type that needs to be an integer then the user will have to change it itself. To change the data type from string to integer, we can use the int()
function.
Suppose a numeric value has a string data type that needs to convert into an integer.
age = "10"
age = int(age)
print(type(age))
# Output: <class 'int'>
In the first line of code, the age variable has a string value that converts into an integer in the next line through the int()
function. Now the age variable can be used with the integer data type.
When we change the data type of data from one to another is called type casting. Python type casting has two types, implicit and explicit type casting. In the implicit, python automatically sets the data type and in explicit user has to set the data type based on the requirement.