Mohit Raj
Posted on December 7, 2019
Type casting:
- In computer science, type conversion, type casting, type coercion, and type juggling are different ways of changing an expression from one data type to another.
- In Python input() function the input taken by the user is a string.
- If we want to take a integer as an input then we have to convert the input into the integer. for this we can use int() function in python.
int function:
The int() function converts the specified value into an integer number.
for example,
i have to string variable and we want to add together then it will generally concatenate both the value .Now if we want to add them because 12 and 13 is simple an integer value and after adding it 12+13=25. here we can use int() function to convert '12'(string 12) into 12(integer 12).
Syntax : int(x)
x='12'
print(type(x))
Output- <class str>
For converting into an int value
int_value=int(x)
print(type(int_value))
output - <class int>
Similarly you can convert y into an integer value.
Now add both and print
- This is generally known as type cast (converting an expression of one data type into other)
float() function:
- The float() method is used to return a floating point number from a number or a string.
- As we convert a variable into int similarly we can type cast a variable into float.
- Syntax: float(x)
- floating numbers are like 12.23 ,34.00,123.9 etc means all number which contain decimal For example
x=12
print(type(x)
y=float(x)
print(type(y)
print(x," is " ,type(x)," value")
print(y," is ",type(y)," value")
Output
<class int>
<class float>
12 is <class int> value
12.0 is <class float> value
There are too many inbuilt function for type casting in python like str(),list(),dict(),tuple(),set() etc i will discussed this all in upcoming tutorials.
If you have any problem then put it in the comment box.
Thank you
Posted on December 7, 2019
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.