- Working in Python
- Collecting user input
- Input needs to be non-negative
- Successfully used While condition in another part of program
- But now don’t understand why this test to capture valid input is failing.
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)
When testing, I entered:
-0.8
I expected this to fail the non-negative test.
But it didn’t, and the invalid input exited the While Loop, and appended the invalid input.
Any assistance is appreciated.
>Solution :
The problem is the expression int(float(xyz_string)). This rounds all your numbers towards zero, so if the number you entered is between 0 and -1, it will be rounded up to zero and pass the test.
To fix this, just delay your int calls until after you’re done getting input:
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))