user10700950
user10700950

Reputation:

Why am I receiving a Type error for this input function

I am trying to write a program that requests the number of seconds between lightning and thunder and reports the distance from the storm rounded to two decimal places.

n = input('Enter the number of seconds between lightning and storm') 
1.25
print('Distance from storm',n/5)

However, when I call the print function, I receive the below error:

Traceback (most recent call last):

   File "<ipython-input-106-86c5a1884a8d>", line 1, in <module>
     print('Distance from storm',n/5)

TypeError: unsupported operand type(s) for /: 'str' and 'int'

How do I solve this?

Upvotes: 0

Views: 227

Answers (2)

Raghavendra Gupta
Raghavendra Gupta

Reputation: 355

You can take the input as in int or float and then proceed with further operations.

n = int(input('Enter the number of seconds between lightning and storm   '))
Enter the number of seconds between lightning and storm   99

print('Distance from storm',n/5)

OutPut:

('Distance from storm', 19)

Upvotes: 1

DirtyBit
DirtyBit

Reputation: 16782

You need to convert your n to a int or a float (which ever suits your requirement) since it is a string:

The input() function returns a string, and therefore you cannot apply the division, hence the error:

TypeError: unsupported operand type(s) for /: 'str' and 'int'

So you need to convert it:

n = input('Enter the number of seconds between lightning and storm')
1.25
print('Distance from storm',int(n)/5)

OUTPUT:

Distance from storm 8.6

Upvotes: 3

Related Questions