Casting in Python | Conversion of datatypes
Casting in python
Casting is conversion of value of a variable from one data type to other
example -- Converting X = 3 ( is a integer) to X = 3.0 (is a float)
There are basically three types of data type
- Casting into integer.
- Casting into string.
- Casting into float.
Casting into integer
Casting float into integer or casting string into integer provided the content of string is a whole number
We use int() for this type of casting.
X = int(3.5) #value of x will be 3
Y= int ("3") #value of y will be treated as integer and we can perform arithmetic operation
Z = int("hello") #this will throw error the value is not whole number
Z = int("hello") #this will throw error the value is not whole number
Casting into string
Casting float into string or casting integer into string
We use str() constructor for casting.
X = str(3) # 3 will be considered as string and arithmetic operation can't be done
Y = str(3.0) #3.0 will be considered as string and arithmetic operation can't be done
Casting into float
We use float() constructor to cast string or integer into float.
It should be kept in mind that a string can only be converted into float if its value is integer or decimal
Questions
1.Take a variable with value 3 and another value 2 use addition operation to add them to get 32 as output and then add 8 to it to get 40
Comments
Post a Comment