I cant figure out how to make a input lock that if the user types in a letter and not a number between 0 and 1000 that it will keep on asking for a number until it gets it. Thanks for any help.

Recommended Answers

All 4 Replies

I make my user input loops follow this pattern:

#Start a loop that will run indefinitely.
while True:
    i = input("Prompt: ")
    #Here I do my input checking. In this example it checks that i isn't an empty string.
    if i:
        #Break out of the indefinite loop.
        break

Check the documentation for try..except statement and the int function.

line 5 of lrh9's code is meant to be

if not i:

That will break if the user entered nothing.

You can expand on that:

# safe numeric input function
# all() needs Python25 or higher

def input_num(prompt="Enter number: "):
    """
    prompt the user for numeric input
    prompt again if the input is not numeric
    return integer or float
    """
    while True:
        # coded for Python3, Python2 uses raw_input()
        # strip() removes any leading or trailing whitespace
        num_str = input(prompt).strip()
        # make sure that all char are of typical number
        if all(c in '+-.0123456789' for c in num_str):
            break
    # float contains period (US)
    if '.' in num_str:
        return float(num_str)
    else:
        return int(num_str)

# testing ...
n = input_num()
print( n, type(n) )
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.