Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

In Python, why is this negative float passing the non-negative while loop test condition?

  • 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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading