A problem with str VS int.

Thomas Passin list1 at tompassin.net
Sun Dec 10 00:23:33 EST 2023


On 12/9/2023 9:42 PM, Steve GS via Python-list wrote:
>   If I enter a one-digit input or a three-digit number, the code works but if I enter a two digit number, the if statement fails and the else condition prevails.
> 
>         tsReading = input("   Enter the " + Brand + " test strip reading: ")
>          if tsReading == "": tsReading = "0"
>          print(tsReading)
>          if ((tsReading < "400") and (tsReading >= "0")):
>              tsDose = GetDose(sReading)
>              print(tsReading + "-" + tsDose)
>              ValueFailed = False
>          else:
>              print("Enter valid sensor test strip Reading.")
> 
> I converted the variable to int along with the if statement comparison and it works as expected.
> See if it fails for you...

I don't have to try it to know it will fail.  You think you are 
comparing numbers but you are comparing strings instead, which won't 
work as you expect.

You would do better to convert the inputs and limits to numbers, as well 
as the GetDose() function.  In a more realistic version, you would also 
have to make sure the user input is legal, either an int or a float, 
whichever you want to work with.

And along those lines (a more realistic version), it would be preferable 
to change the limits to be named constants, which will make the code 
easier to understand and change when it's revisited later.  Something 
like this:

UPPER = 400
LOWER = 0
# ...
if LOWER < value < UPPER:
     # .....



More information about the Python-list mailing list