【问题标题】:Invalid syntax for except ValueError除了 ValueError 的语法无效
【发布时间】:2026-01-27 17:00:01
【问题描述】:

当我运行这段代码时(Python 3.3):

counter=0
score=0
import random
a = random.randint(1,25)
b = random.randint(1,25)
c=a+b
try:
    answer=int(input("What is "+str(a)+" + "+str(b)+" ? ")                
    if answer == c:
        score=score+1
        print("Well done!")
        print("Your score is "+str(score)+".")
        print("")
        counter = counter + 1
    else:
        print("Thats wrong. The correct asnwer is: "+str(c)+".")
        print("Your score is "+str(score)+".")
        print("")
        counter = counter + 1
except ValueError:
       print("sadas")

我说“无效语法”,它突出显示“if answer == c:”红色的冒号。

【问题讨论】:

  • 上一行缺少右括号。

标签: python python-3.3 except


【解决方案1】:

您缺少右括号:

answer=int(input("What is "+str(a)+" + "+str(b)+" ? ")                
#         ^     ^                                    ^?
#         |      \----------------------------------/ |
#          \-----------------------------------------/

【讨论】:

  • 抱歉,我不知道这个功能。我接受了你的回答。