Dou*_*lva 27 python python-3.x
我正在学习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')
Run Code Online (Sandbox Code Playgroud)
我明白了
TypeError:'str'和'int'实例之间不支持'<='
但我这里没有任何字符串,所有变量都是整数.
X33*_*X33 39
更改
vote = input('Enter the name of the player you wish to vote for')
Run Code Online (Sandbox Code Playgroud)
至
vote = int(input('Enter the name of the player you wish to vote for'))
Run Code Online (Sandbox Code Playgroud)
您将从控制台获取输入作为字符串,因此必须将该输入字符串强制转换为int对象才能执行数值运算.
McG*_*ady 15
如果您使用Python3.x input将返回一个字符串,那么您应该使用int方法将字符串转换为整数.
如果存在prompt参数,则将其写入标准输出而不带尾随换行符.然后,该函数从输入中读取一行, 将其转换为字符串(剥离尾部换行符),然后返回该行.读取EOF时,会引发EOFError.
顺便说一句,try catch如果你想将字符串转换为int ,这是一个很好的使用方法:
try:
i = int(s)
except ValueError as err:
pass
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助.
| 归档时间: |
|
| 查看次数: |
249129 次 |
| 最近记录: |