类型错误:“str”和“int”的实例之间不支持“<=”

2024-06-16 13:23:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在学习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: '<=' not supported between instances of 'str' and 'int'

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


Tags: andofthe代码编码列表inputpython3
3条回答

如果您使用的是Python3.xinput将返回一个字符串,因此应该使用int方法将字符串转换为整数。

Python3 Input

If the prompt argument is present, it is written to standard output without a trailing newline. The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that. When EOF is read, EOFError is raised.

顺便说一下,如果您想将字符串转换为int,那么使用trycatch是一个很好的方法:

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

希望这有帮助。

使用输入函数时,它会自动将其转换为字符串。你得走了:

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

将输入转换为int类型值

改变

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对象才能执行数值运算。

相关问题 更多 >