Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/oracle/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 错误处理不起作用_Python - Fatal编程技术网

Python 错误处理不起作用

Python 错误处理不起作用,python,Python,我的错误处理代码不工作。我试着做以下工作:如果用户输入除1、2或3之外的任何输入,那么用户应该得到错误消息,while循环应该再次启动 但是,我的代码不起作用。有什么建议吗 def main(): print("") while True: try: number=int(input()) if number==1: print("hei") if number==2: print("bye"

我的错误处理代码不工作。我试着做以下工作:如果用户输入除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()

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

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

错误消息是什么?此外,缩进完全错误,会导致严重的语法问题。你能解决这个问题吗?确保你的
除了
缩进到与你的
try
相同的级别?为什么你需要try。。。除了第一点之外?同样,这是一个无限循环…@JulienSpronck,因为
int
将在来自
input()
的不可转换输入时引发
ValueError
-但是是的,它确实需要中断:)