【问题标题】:TypeError: unsupported operand type(s) for /: 'str' and 'str'TypeError:不支持的操作数类型/:'str'和'str'
【发布时间】:2013-02-20 13:21: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')

每当我运行这个程序时,我都会得到这个

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

如何将 pyc 除以 tpy?

【问题讨论】:

    标签: python typeerror operand


    【解决方案1】:

    改为将它们转换为整数:

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

    在 python 3 中,input() 函数返回一个字符串。总是。这是对 Python 2 的改变; raw_input() 函数已重命名为 input()

    【讨论】:

    • 或者,如果您需要接受不是整数的数字,也可能是floats 或decimal.Decimals。
    【解决方案2】:

    您应该做的第一件事是学习阅读错误消息。它告诉你什么 - 你不能使用除法运算符的两个字符串。

    所以,问问自己为什么它们是字符串以及如何使它们成为非字符串。它们是字符串,因为所有输入都是通过字符串完成的。制作 then 非字符串的方法是转换它们。

    将字符串转换为整数的一种方法是使用int 函数。例如:

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

    【讨论】:

      【解决方案3】:

      我会写:

      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
      

      【讨论】:

      • 谢谢,我是编程新手,我从来不知道这样做
      • 如果您要添加错误处理,您可能需要一个except ValueError 子句来处理无效输入...
      【解决方案4】:

      forwars=d 斜杠还有另一个错误。

      if we get this : def get_x(r): return path/'train'/r['fname']
      is the same as def get_x(r): return path + 'train' + r['fname']
      

      【讨论】:

        【解决方案5】:
        name = input ('What is your name?: ')
        age = input('How old are you?: ')
        date = input ('What year is it?: ')
        year = (int(date) - int(age) + 100)
        
        print('You\'ll be 100 in the year ', year)
        
        
        
        
        #That's how I decided to hardcode it. You could get more specific with actual birthdates or else it'll probably be off by a year unless your bday passed.
        

        【讨论】:

        • 此答案与该问题的其他两个答案重复,因此不会为帖子添加任何有用的内容。
        猜你喜欢
        • 2018-12-06
        • 1970-01-01
        • 2021-01-03
        • 2018-04-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多