0

Hi everybody,

I'm trying to write a function that takes in 2 values, a min and a max, that prompts the user to enter a value within that range, and uses 0 as a sentinel to quit the loop.

My issue is, I also want the loop to continue prompting the user when the user enters nothing (i.e. hits enter) until a value between the range is entered. How do I go about doing this with the code I have already written? Thanks!

def getValidNum(min, max):
    QUESTION = "Enter a value, 0 to quit: "

    num = input(QUESTION)

    while num != 0:
        if num in range(min, max + 1):
            return num    
        else:
            print("Sorry %d - %d or 0 only") % min, max
            print("Try again.")
            num = input(QUESTION)
5
Contributors
4
Replies
5
Views
7 Years
Discussion Span
Last Post by pythopian
0

Hi everybody,

I'm trying to write a function that takes in 2 values, a min and a max, that prompts the user to enter a value within that range, and uses 0 as a sentinel to quit the loop.

My issue is, I also want the loop to continue prompting the user when the user enters nothing (i.e. hits enter) until a value between the range is entered. How do I go about doing this with the code I have already written? Thanks!

def getValidNum(min, max):
    QUESTION = "Enter a value, 0 to quit: "

    num = input(QUESTION)

    while num != 0:
        if num in range(min, max + 1):
            return num    
        else:
            print("Sorry %d - %d or 0 only") % min, max
            print("Try again.")
            num = input(QUESTION)

try using a Boolean variable and put it in condition of while when you want to break the loop say it false and when you think it should keep running say it true.
something like

flag = True
while num != 0 and flag

then you can also use flag to control your loop

Edited by sfar_furqan: n/a

0

You can do it like this.

def getValidNum(min, max):
    print ('Enter a value between %d and %d | 0 to quit' % (min, max))
    while True:
        try:
            num = input('>')
            if int(num) in range(int(min), int(max)):
                print (num)  #test print
                #return num
            elif num == '0':
                exit()
            else:
                print('Only values between %d and %d' % (min, max))
                print("Try again.")
        except ValueError:
            print('Numbers only,try again')

getValidNum(2, 8)

Edited by snippsat: n/a

0

You can do it like this.

def getValidNum(min, max):
    ....
            elif num == '0':
                break # instead of exit()
    ....

Rather use break instead of exit() . You don't probably want to abort the whole program at that point.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.