使用except块

时间:2020-04-23 06:00:51

标签: python function input while-loop try-except

我叫Ana Baird,我正在用try和except块编写程序。 我必须要求用户输入选择1到12之间的数字,但是如果用户输入数字0或13会怎样?还是大于12的数字?我应该在except块中键入哪种错误来捕获此错误?

此外,在新的def功能中,我必须放置一个菜单并将其打印出来,那么如何首先打印该菜单,以便用户可以看到它,然后才能从该菜单中选择一个数字?该菜单必须在功能内部吗?

例如,这是我尝试的第二个问题:

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")

第三个问题:如何要求用户输入1到12之间的数字,并继续要求该用户继续输入,直到他们输入“完成”为止?我尝试了while循环,但它不断进入打印语句的无限循环,例如

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

以此类推

有什么想法吗?感谢您的帮助,谢谢!另外,请使其成为一个简单的程序,而不是过于复杂的程序,我只是一个初学者,谢谢。

此致, 安娜·贝尔德

2 个答案:

答案 0 :(得分:0)

此处:

if userInp >= 1 and userInp <= 12:
    # 1 - 12
else:
    # error msg

答案 1 :(得分:0)

关于您的第一个问题: 您可以定义一个custom exception并将其引发。

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))

关于第二个问题: 定义变量menu = print(...)没有意义。 这是您要找的吗?

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: ")

关于您的第三期: 尝试进行while True:循环,并包括可以破坏无限循环的检查:

if userInp == 'done':
    break