Table of contents
Namaste Coders !
In this article, we will learn about typecasting, how to explicitly change one datatype to another.
There may be times when you want to specify a type on to a variable. This can be done with casting. Python defines type conversion functions to directly convert one data type to another. It is very handy and is required in day to day programming.
- int(a,base) : This function converts any data type to integer. ‘Base’ specifies the base in which string is if data type is string.
In this example, we mentioned base 2 which is binary.
- float() : This function is used to convert any data type to a floating point number.
- ord() : This function is used to convert a character to integer.
- hex() : This function is to convert integer to hexadecimal string.
- oct() : This function is to convert integer to octal string.
- list(): This function is used to convert any data type which is iterable like a string, tuple to a list type.
- tuple(): This function is used to convert to a tuple. It also converts only iterable datatypes.
- set(): This function returns the type after converting to set.It will take only unique elements.
Python Input/Output
We take input from users in python using input() function. It takes the input only in string type.
Now if you want to display any message like what you want a user to enter then we can do it in this format:
To take any other datatype as input we have to explicitly mention it by using type conversion.for example: I want the user’s age which is of int type. We can do so like this:
similarly, if you want float value:
The End
I hope you enjoyed the article and had a good learning experience.
Follow for more articles and keep sharing👩
Keep coding