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)

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

if num == "":
    #do something here

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)

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.