Friday, June 30, 2023

Typecasting

Typecasting is required to convert a value from one data type to another. You just saw an example in the last section where the value of price and quantity obtained by the user were in string format and were converted into integer and float values respectively with the help of typecasting.

Typecasting is a very simple and straightforward approach used to convert a variable from one data type to another data type.

Let’s say there are three variables num1, num2, and num3 as follows:

>>> num1 = 4

>>> type(num1)

<class 'int'>

>>> num2 = 3.6

>>> type(num2)

<class 'float'>

>>> num3 = 'dog'

>>> type(num3)

Now, let’s try to change the value of each variable to another type.

>>> num11 = float(4)

>>> num11

4.0

>>> type(num11)

<class 'float'>

>>> num22 = str(num2)

>>> type(num22)

<class 'str'>

>>> num33 = int(num3)

Traceback (most recent call last):

File "<pyshell#12>", line 1, in <module>

num33 = int(num3)

ValueError: invalid literal for int() with base 10: 'dog'

>>>

So, you see, you can convert numeric from one type to another and you can convert a numeric value to a string value but a string value cannot always be converted to a numeric value. Only if the string consists of a numeric value, can it be converted to a numeric data type. Following are some examples of typecasting a string into numeric values. Do have a look and don’t forget to experiment yourself.

a.

>>> str1 ='3.7'

>>> float(str1)

3.7

b.

>>> str2 = '3.7'

>>> int(str2)

Traceback (most recent call last):

File "<pyshell#16>", line 1, in <module>

int(str2)

ValueError: invalid literal for int() with base 10: '3.7'

c.

>>> str4 = '4.8'

>>> x = float(str4)

>>> int(x)

4

>>>

The problem in the example (b) can be resolved by first converting the string to float and then converting the float value to integer. This is shown in example(c) and another way is as follows:

>>> str2 = '3.7'

>>> int(float(str2))

3

>>>

Now that you have learned about typecasting, you would have also understood the importance of typecasting the user input into the right type before using it for any kind of arithmetic calculations.

Now Write a program to convert the value in grams (gm) into Kgs.

Answer:

gm = float(input("Enter value in Grams : "))

kg = gm/1000

print(gm,"grams = ",kg," Kgs.")

Output

Enter value in Grams : 8

8.0 grams = 0.008 Kgs.

>>>

Since a new value of 656 has been assigned to the reserved word ‘int’, you cannot use it for typecasting a float value to integer code. This code will generate a TypeError as follows:

Traceback (most recent call last):

File "<pyshell#3>", line 1, in <module>

int(num1)

TypeError: 'int' object is not callable

Share:

0 comments:

Post a Comment