Python: else ValueError: (Specifically ValueError In This Case)

Python: else ValueError: (Specifically ValueError In This Case)

我有一个与我的代码无关的问题。我只是好奇。为什么我(我不了解你)只能在 try 和 except 循环中使用 ValueError?例如:

print("What is 1 + 1?")
while(True):
    try:
        UserInput = int(input(("Your answer here:"))
        if(UserInput == 2):
            print("Congratulations you are correct!")
            break
        else:
            print("That is incorrect. Try again!")
    except ValueError:
        print("That is not a number. Try again!")

这工作得很好(或者至少应该)但是,为什么(如果不能)下一段代码不能工作。

print("What is 1 + 1?")
while(True):
    UserInput = int(input("Your answer here:"))
    if(UserInput == 2):
        print("Congratulations you are correct!")
        break
    elif(UserInput != 2):
        print("That is incorrect. Try again!")
    else(ValueError):
        print("That is not a number. Try again!")

当我 运行 这个时,我得到这个错误:

Traceback (most recent call last):
  File "python", line 9
    else(ValueError):
        ^
SyntaxError: invalid syntax

我知道这是因为 ValueError 只适用于(我认为)try 和 except 循环但是,为什么它不能在上述情况下工作?我假设他们会给出相同的结果,但是,我不知道一切。也许你们中的一个非常聪明的人可以告诉我我的行不通或替代方案。感谢您尝试向我澄清这一点 :)。

第二个示例中的 SyntaxError 来自 else 不需要条件的事实。第一个例子完全没问题

更好的是,让 try-block 尽可能短:

print("What is 1 + 1?")
while True:
    try:
        UserInput = int(input(("Your answer here:"))
    except ValueError:
        print("That is not a number. Try again!")
    else:
        if UserInput == 2:
            print("Congratulations you are correct!")
            break
        else:
            print("That is incorrect. Try again!")

tryexcept 是控制流的一种形式。本质上就是try到运行这段代码,except如果出现异常(比如ValueError)做其他事情。

ifelse 是另一种形式的控制流。它们一起表示 if 条件为真,做某事; else,做点别的。

发生异常不是条件,因此使用 elseValueError 这样的异常是没有意义的。相反,您想使用 try/except 块。