TypeCasting In Python

TypeCasting In Python

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.

3.png

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.

4.png

  • ord() : This function is used to convert a character to integer.

23.PNG

  • hex() : This function is to convert integer to hexadecimal string.

24.PNG

  • oct() : This function is to convert integer to octal string.

25.PNG

  • list(): This function is used to convert any data type which is iterable like a string, tuple to a list type.

26.PNG

  • tuple(): This function is used to convert to a tuple. It also converts only iterable datatypes.

27.PNG

  • set(): This function returns the type after converting to set.It will take only unique elements.

28.PNG

Python Input/Output

We take input from users in python using input() function. It takes the input only in string type.

29.PNG

Now if you want to display any message like what you want a user to enter then we can do it in this format:

30.PNG

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:

31.PNG

similarly, if you want float value:

32.PNG

The End

I hope you enjoyed the article and had a good learning experience.

Follow for more articles and keep sharing👩

Keep coding

Linkedin

hashnode blogs

Did you find this article valuable?

Support akshita garg's blog by becoming a sponsor. Any amount is appreciated!