所以我又来了,像往常一样不知所措。我是一个新手,所以这可能是咬了超过我可以咀嚼,但无论如何。 这个程序的目的是提供一个基于用户输入值的输出。如果用户没有输入正确的输入,它将实现一个输入陷阱
我试图使它这样一个字母或非整数值的输入会导致消息“请只输入整数。”它适用于浮点,但不适用于字母。我应该注意到,“输入一个介于0和10之间的数字”消息工作正常。 此外,循环应该在用户输入“done”时关闭,但这只会导致“ValueError:could not convert string to float:'done'”
我没有用While-True的格式写这篇文章,因为对于我来说,摆脱While循环的写作方法更舒服
setCount = 1
allScore = 0
done = False
while not done:
strScore = float (input ( "Enter Set#" + str(hwCount) + " score: "))
if (strScore == int (strScore) and strScore >=0 and strScore <=10):
totalScore = totalScore + (strScore)
setCount = setCount + 1
elif ( setScore == int (strScore) and( setScore < 0 or setScore > 10)):
print ("Please enter a number between 0 and 10.")
elif setScore != "done":
print ("Please enter only whole numbers.")
else:
done = True
你真的应该清理你的代码,所有这些额外的空间伤害可读性。我建议使用PyLint(
pip install pylint
,pylint file.py
)我不会太重构你的代码,但是你需要在转换成一个float之前检查“done”。如果有人输入了无效的答案,您需要捕捉ValueErrors并优雅地处理它
这是你的程序的一个更完整的版本,供参考。这就是我重构它的方式
您可以立即将输入字符串转换为读字符串所在行上的浮点值:
为了接受“done”作为输入,您需要将其作为字符串保存,并在完成所有输入验证后将其转换为float(或int)
删除
float()
,strScore将是一个字符串。然后检查是否等于“完成”。最后,将其转换为try块中的整数相关问题 更多 >
编程相关推荐