【问题标题】:TypeError: '<=' not supported between instances of 'str' and 'int' [duplicate]TypeError:'str'和'int'的实例之间不支持'<=' [重复]
【发布时间】:2023-04-08 14:39:01
【问题描述】:

我正在学习 python 并进行练习。其中之一是编写一个投票系统,以使用列表在比赛的 23 名球员中选出最佳球员。

我正在使用Python3

我的代码:

players= [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
vote = 0
cont = 0

while(vote >= 0 and vote <23):
    vote = input('Enter the name of the player you wish to vote for')
    if (0 < vote <=24):
        players[vote +1] += 1;cont +=1
    else:
        print('Invalid vote, try again')

我明白了

TypeError:“str”和“int”的实例之间不支持“

但我这里没有任何字符串,所有变量都是整数。

【问题讨论】:

    标签: python python-3.x


    【解决方案1】:

    改变

    vote = input('Enter the name of the player you wish to vote for')
    

    vote = int(input('Enter the name of the player you wish to vote for'))
    

    您从控制台获取输入作为字符串,因此您必须将该输入字符串转换为 int 对象才能进行数值运算。

    【讨论】:

      【解决方案2】:

      如果你使用 Python3.x input 会返回一个字符串,所以你应该使用int 方法将字符串转换为整数。

      Python3 Input

      如果提示参数存在,则将其写入标准输出 没有尾随换行符。然后该函数从输入中读取一行, 将其转换为字符串(去除尾随的换行符),然后返回 那。读取 EOF 时,会引发 EOFError。

      顺便说一句,如果要将字符串转换为int,使用try catch 是一个好方法:

      try:
        i = int(s)
      except ValueError as err:
        pass 
      

      希望这会有所帮助。

      【讨论】:

        【解决方案3】:

        当您使用输入函数时,它会自动将其转换为字符串。你需要去:

        vote = int(input('Enter the name of the player you wish to vote for'))
        

        将输入转换为 int 类型值

        【讨论】:

          【解决方案4】:

          input() 默认采用字符串形式的输入。

          if (0<= vote <=24):
          

          vote 接受字符串输入(假设 45 等)并变得无法比较。

          正确的方法是:vote = int(input("Enter your message")将输入转换为整数(4 转换为 4 或 5 转换为 5,具体取决于输入)

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2018-12-17
            • 2021-06-06
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多