Validate the user’s input with while, break, and continue

See break and continue. We saw the try and except here.

validate.py

Please type an integer in the range 1 to 10 inclusive: hello
Sorry, hello is not an integer.
Please type an integer in the range 1 to 10 inclusive: 5.6
Sorry, 5.6 is not an integer.
Please type an integer in the range 1 to 10 inclusive: 11
Sorry, 11 is not in the range 1 to 10 inclusive.
Please type an integer in the range 1 to 10 inclusive: 0
Sorry, 0 is not in the range 1 to 10 inclusive.
Please type an integer in the range 1 to 10 inclusive: 7
Thank you.  7 is acceptable.

Things to try

  1. Unlike most languages, Python lets you abbreviate
        if 1 <= i and i <= 10:
    
    to
        if 1 <= i <= 10:
    
    See Chained.

  2. Make a user-defined function.
    """
    validate.py
    
    Keep prompting the user until he or she inputs an integer in the range 1 to 10
    inclusive.
    """
    
    import sys
    
    def getInt(prompt):
        """
        Let the user input one integer.
        """
        assert isinstance(prompt, str)
    
        while True:
            try:
                s = input(prompt + " ")
            except EOFError:
                sys.exit(1)
    
            try:
                i = int(s)
            except ValueError:
                print(f"Sorry, {s} is not an integer.  Try again.")
                continue    #Go back up to the word while
    
            return i
    
    
    while True:
        i = getInt("Please type an integer in the range 1 to 10 inclusive:")
    
        if 1 <= i and i <= 10:
            break
    
        print(f"Sorry, {i} is not in the range 1 to 10 inclusive.  Try again.")
    
    print(f"Thank you.  {i} is acceptable.")
    sys.exit(0)
    

  3. Give the user only three chances to type in a valid number. If he or she hasn’t done it by then, exit the script with exit status 1.