0

If, Elif, Else with negative numbers.

January 25, 2023

Having some issues getting this to work – if the nubmer is negative, it doesn’t act as I’d expect.

# Python3
'''
BZ value pulled from .JSON - ranges between +30 and -30

if # above -5 = Green  (up through zero and to positiveq)
if # between -6 and -14 = Yellow
if # less than -15 = Red
if other = Gray
'''

bz = input("What is the BZ? ")                          #user input for ease of testing

if bz >= '-5':                                          # Anything greater than or equal to -5 (through +infinity)
    print("BZ = {}. Color should be Green".format(bz))
elif bz <= '-6' and bz <= '-14':                        # Values -6 through -14
    print("BZ = {}. Color should be Yellow".format(bz))
elif bz <= '-15':                                       # values less than -15 (through -infinity)
    print("BZ = {}. Color should be RED".format(bz))
else:                                                   # Anything else, don't error, assign generic.
    print("BZ = {}. Color should be Gray".format(bz))

With some help from the braintrust that is people on FaceBook (and a little StackExchange), we worked it down to numerical comparison operators on string values. Switching BZ to an INT helped, as well as making the if, elif statement work with absolutes – but it didn’t handle decimals. A float ended up doing what was needed.

Also fixed 2 gaps that cold have happened in the data: between -5 and -6, as well as -14 and -15. The resulting code is below.

# Python3
'''
BZ value pulled from .JSON - ranges between +30 and -30

if # above -5 = Green  (up through zero and to positiveq)
if # between -6 and -14 = Yellow
if # less than -15 = Red
if other = Gray
'''

bz = input("What is the BZ? ")
bz = float(bz)                         #user input for ease of testing

if bz > -6:                                          # Anything greater than or equal to -5 (through +infinity)
    print("BZ = {}. Color should be Green".format(bz))
elif bz <= -6 and bz > -15:                        # Values -6 through -14
    print("BZ = {}. Color should be Yellow".format(bz))
elif bz <= -15:                                       # values less than -15 (through -infinity)
    print("BZ = {}. Color should be RED".format(bz))
else:                                                   # Anything else, don't error, assign generic.
    print("BZ = {}. Color should be Gray".format(bz))