Home > Enterprise >  How can I get the input and see if its in range and get the number again if its not in the range?
How can I get the input and see if its in range and get the number again if its not in the range?

Time:12-02

while True:
a = int(input("Enter a number 1: "))
if a in range(121):
    pass
else:
    print("Out of Range")
b = int(input("Enter a number 2: "))
if b in range(121):
    pass
else:
    print("Out of Range")

c =int(input("Enter a number 3: "))
if c in range(121):
    pass
else:
    print("Out of Range")

if a b c == 120:
    break
else:
    print("Incorrect Total")

I want to check the if the input number is in range and if not get the same number again and at last check if the 3 variable inputs add upto 120 and if not ask for the 3 numbers again but In the above code I cant get it to ask for the same number when its out of range.

CodePudding user response:

You need to loop the input call

while True:
    a = int(input("Enter a number 1: "))
    if a in range(121):
        break
    else:
        print("Out of Range")

CodePudding user response:

You had the right idea, but the looping was a bit messed up. This will keep asking until you enter a "good" value. If the total isn't right, it we restart as per requirement.

def get_input(n):
    inp = -1
    while inp not in range(121):
        inp = int(input(f"Enter a number {n}: "))  # f-strings require python >= 3.6
    return inp
    
while True:
    a = get_input(1)
    b = get_input(2)
    c = get_input(3)
    
    if a   b   c == 120:
        break
    else:
        print("Incorrect Total")
  • Related