0

to preface, this issue arises within a while loop, inside a for loop, inside a function. The while loop is supposed to take an input from the user and break once a set variable is discovered (a number between 1 and 5) however, when I was bug fixing I found that it would loop on a negative, say -9, but if I put in a positive, say 9, then a negative, it would break the loop. I am super stumped on what I have done that allows this bypass as it will loop infinitely in the negatives and the positives, but doesn't loop infinitely if a positive is input followed by a negative.

 while food.isdigit() == True:
        if int(food) >= 1 and int(food) <= 5:
            break
        else:
            print (invalid_score)


            food = input(f"Critic {number} Food Score: ")

I have tried the following but it still breaks the while loop after taking an incorrect positive integer followed by an incorrect negative integer.

while food.isdigit() == True:
        if int(food) >= 1 and int(food) <= 5:
            break
        elif int(food) < 1 or int(food) > 5:
            print (invalid_score)
            food = input(f"Critic {number} Food Score: ")
2
  • Maybe this link will provide you with a way to make your code handle the negative numbers. isdigit negative Commented Jul 29, 2022 at 3:11
  • It appears that the problem involves more code than what you've provided. Please provide the code for the entire function. Commented Jul 29, 2022 at 4:53

1 Answer 1

0

After another few hours of research, I discovered the try/except commands, these commands allowed me to check for an integer before checking for a string all within the same while loop.

a = input()
while True:
    try:
        if int(a) == x:
            break
        else:
            print("invalid")
            a = input()
    except:
        if (a) == "valid":
            break
        else:
            print("invalid")
            a = input()

This allows the while loop to search for key phrases, as well as integers of a specific value without leaving the while loop at all, allowing it to check for all variables as many times as necessary.

here is the link to the original stack overflow post that helped me solve the mystery: can I use string and integer in while loop in python?

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.