0

my name is Ana Baird, and I'm writing a program with the try and except block. I have to ask the user for input in selecting a number between 1 and 12, but what if a user inputs a number 0 or a 13? Or any number bigger than 12? What kind of error should I type in the except block to catch this error?

Also, in a new def function, I have to put a menu and print it out, so how do I first print the menu so that the user can see it before they can select a number from that menu? This menu has to be inside the function?

So, for instance, this is my attempt with the second issue:

userInp = int(input("Please enter a number between 1 and 12 from the menu: ")

    def printMenu()
        menu = print("\t\t1)Category\n\t\t2)Item\n\t\t3)Serving Size\n\t\t4)Calories")

A third issue: How do I ask a user to input a number from 1 to 12 and keep asking that user to keep entering input until they input "done"? I tried with the while loop but it just keeps going into an infinite loop of a print statement, like

"you selected Item
you selected Item
You selected Item
..."

and so on

Any ideas? I appreciate the help, thank you! Also, please make it a simple program, not an overcomplicated one, I'm just a beginner, thank you.

Sincerely, Ana Baird

Ana Baird
  • 1
  • 3
  • Does this answer your question? [Asking the user for input until they give a valid response](https://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they-give-a-valid-response) – Gino Mempin Apr 23 '20 at 06:37

2 Answers2

0

here:

if userInp >= 1 and userInp <= 12:
    # 1 - 12
else:
    # error msg
rn0mandap
  • 333
  • 1
  • 8
  • thanks, but it can't be in an if/else statement; I clearly asked how to do it in an TRY/EXCEPT statement. Thank you anyway. – Ana Baird Apr 23 '20 at 06:15
0

Regarding your first issue: You could define a custom exception and raise it.

class IncorrectInput(Exception):
    pass

def enter_number():
    try:
        userInp = int(input("Please enter a number between 1 and 12 from the menu: "))
        if userInp < 1 or userInp > 12:
            raise IncorrectInput
        return userInp
    except IncorrectInput as e:
        # Handle the exception.
        print("Number should be between 1 and 12.")
        return None

if __name__ == '__main__':
    my_number = enter_number()
    print('Output of enter_number(): {}'.format(my_number))

Regarding your second issue: There is no point in defining a variable menu = print(...). Is this what you are looking for?

def printMenu():
    print("\t\t1)Category\n\t\t2)Item\n\t\t3)Serving Size\n\t\t4)Calories")

printMenu()
userInp = int(input("Please enter a number between 1 and 12 from the menu: ")

Regarding your third issue: Try a while True: loop, and include a check that can break the infinite loop:

if userInp == 'done':
    break
Elias Strehle
  • 1,722
  • 1
  • 21
  • 34