A problem with str VS int.
dn
PythonList at DancesWithMice.info
Sun Dec 10 00:53:11 EST 2023
On 10/12/23 15:42, 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...
It works as expected (by Python)! This is how strings are compared -
which is not the same as the apparently-equivalent numeric comparison.
Think about what you expect from the code below, and then take it for a
spin (of mental agility):
values = [ 333, 33, 3, 222, 22, 2, 111, 11, 1, ]
print( sorted( values ) )
strings = [ "333", "33", "3", "222", "22", "2", "111", "11", "1", ]
print( sorted( strings ) )
The application's data appears numeric (GetDose() decides!).
Accordingly, treat it so by wrapping int() or float() within a
try-except (and adjusting thereafter...).
"But wait, there's more!"
(assuming implement as-above):
if 0 <= ts_reading < 400:
1 consistent 'direction' of the comparisons = readability
2 able to "chain" the comparisons = convenience
3 identifier is PEP-008-compliant = quality and style
--
Regards,
=dn
More information about the Python-list
mailing list