TypeError: unsupported operand type(s) for /: '

2019-01-06 23:33发布

name = input('Enter name here:')
pyc = input('enter pyc :')
tpy = input('enter tpy:')
percent = (pyc / tpy) * 100;
print (percent)
input('press enter to quit')

whenever i run this program i get this

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

what can i do to divide pyc by tpy?

3条回答
SAY GOODBYE
2楼-- · 2019-01-07 00:11

The first thing you should do is learn to read error messages. What does it tell you -- that you can't use two strings with the divide operator.

So, ask yourself why they are strings and how do you make them not-strings. They are strings because all input is done via strings. And the way to make then not-strings is to convert them.

One way to convert a string to an integer is to use the int function. For example:

percent = (int(pyc) / int(tpy)) * 100
查看更多
女痞
3楼-- · 2019-01-07 00:21

I would have written:

percent = 100
while True:
     try:
        pyc = int(input('enter pyc :'))
        tpy = int(input('enter tpy:'))
        percent = (pyc / tpy) * percent
        break
     except ZeroDivisionError as detail:
        print 'Handling run-time error:', detail
查看更多
做个烂人
4楼-- · 2019-01-07 00:22

By turning them into integers instead:

percent = (int(pyc) / int(tpy)) * 100;

In python 3, the input() function returns a string. Always. This is a change from Python 2; the raw_input() function was renamed to input().

查看更多
登录 后发表回答