0
votes

I got two loops, the first loop checks whether the given value is an int, if so it jumps to the second loop, which checks if the given value is negative. However, if I were to give a negative int input, it would logically jump to the second loop which checks if it's negative. So in the case I put -2, integer_check will be True but if my next value will be -2.2 there won't be a integer_check since it's already True.

while (integer_check == False):
     try:
         integer = int(input(" :"))
     except ValueError:
         continue
     else:
         integer_check = True

while (integer < 0) and (integer_check == True):
    integer = int(input(" :"))

So in case of: negative integer > negative/positive float my code breaks. Any help is greatly appreciated.

1
Change integer = True to integer_check = True in the else in your first loopinspectorG4dget
Whoops wasn't supposed to be like that, my variables were in a different language so I messed up changing the names.LLScheme

1 Answers

2
votes

The Pythonic way to do this is to wrap the whole thing in a while True and loop until you've passed all validation, then break.

while True:
    integer = input(" :")
    try:
        integer = int(integer)
    except ValueError:
        print("Must enter a number")
        continue
    if integer < 0:
        print("Must enter a positive number")
        continue
    else:
        break

I rather prefer a Go idiom for this, however, but note that this is not preferred in Python.

def validate(input_) -> (int, bool):
    integer, ok = -1, False
    try:
        integer = int(input_)
    except ValueError:
        pass
    else:
        if integer >= 0:
            ok = True
    return integer, ok

while True:
    integer, ok = validate(input(" :"))
    if ok:
        break