错误处理无法正常工作

时间:2015-03-22 23:33:00

标签: python

我的错误处理代码无效。我尝试执行以下操作:如果用户输入除1,2或3之外的任何输入,则用户应该收到错误消息并且应该再次启动while循环。

但是我的代码无效。有什么建议吗?

def main():
print("")
while True:
    try:
        number=int(input())
        if number==1:
            print("hei")
        if number==2:
            print("bye")
        if number==3:
            print("hei bye")
        else:
            raise ValueError
except ValueError:
    print("Please press 1 for hei, 2 for bye and 3 for hei bye")

 main()

1 个答案:

答案 0 :(得分:2)

你也可以在这里更好地使用异常处理来处理这种情况,例如:

def main():
    # use a dict, so we can lookup the int->message to print
    outputs = {1: 'hei', 2: 'bye', 3: 'hei bye'}
    print() # print a blank line for some reason
    while True:
        try:
            number = int(input()) # take input and attempt conversion to int
            print(outputs[number]) # attempt to take that int and print the related message
        except ValueError: # handle where we couldn't make an int
            print('You did not enter an integer')
        except KeyError: # we got an int, but couldn't find a message
            print('You entered an integer, but not, 1, 2 or 3')
        else: # no exceptions occurred, so all's okay, we can break the `while` now
            break

main()