在Python中,为什么这个负浮点数能够通过非负while循环测试条件?

问题描述 投票:0回答:1
  • 使用Python
  • 收集用户输入
  • 输入必须为非负数
  • 在程序的另一部分成功使用了While条件
  • 但现在不明白为什么这个捕获有效输入的测试失败了。
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 循环,并追加了无效输入。

如有任何帮助,我们将不胜感激。

python validation input while-loop
1个回答
0
投票

问题在于表达方式

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))
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.