print("How many grams of xyz are required?")
xyz_string = input()
xyz = int(float(xyz_string))
while xyz < 0:
print("Sorry, the amount must be a non-negative number. Please try again.")
print("How many grams of xyz are required")
xyz_string = input()
xyz = int(float(xyz_string))
all_xyz.append(xyz)
测试时,我输入:
-0.8
我预计这不会通过非阴性测试。 但事实并非如此,无效输入退出了 While 循环,并追加了无效输入。
如有任何帮助,我们将不胜感激。
问题在于表达方式
int(float(xyz_string))
。这会将您的所有数字四舍五入到零,因此如果您输入的数字在 0 和 -1 之间,它将被四舍五入到零并通过测试。
要解决此问题,只需延迟
int
调用,直到完成获取输入即可:
print("How many grams of xyz are required?")
xyz_string = input()
xyz = float(xyz_string)
while xyz < 0:
print("Sorry, the amount must be a non-negative number. Please try again.")
print("How many grams of xyz are required")
xyz_string = input()
xyz = float(xyz_string)
all_xyz.append(int(xyz))