我试图验证用户输入以查看它是否在1到500的范围内。 以下是我提出的代码:
while teamScore not in range (1,501):
print "The score is not in the valid range!"
teamScore=raw_input("Please enter the team score (1-500): ")
但是,当我运行代码时,除了声明0和900无效外,它不接受正确的数字,例如34,79,200。
我想仍然使用我的while循环,任何人都可以启发我如何修改我的代码? 提前谢谢!!
答案 0 :(得分:0)
raw_input
返回包含用户输入的字符串。您的while循环使用该字符串并检查它是否在整数范围内。将teamscore
变量转换为整数。
while teamScore not in range (1,501):
print "The score is not in the valid range!"
teamScore=raw_input("Please enter the team score (1-500): ")
try:
teamScore = int(teamScore)
except ValueError:
teamScore = 0
答案 1 :(得分:0)
while teamScore not in range (1,501):
print "The score is not in the valid range!"
teamScore=int(raw_input("Please enter the team score (1-500): "))
raw_input()返回一个字符串,你应该把它转换成int。