首页 > 解决方案 > try:/except: 尝试运行模块时在 Python 中返回语法错误

问题描述

下面是我的代码,错误在第 4 行“except”给出了一个语法错误......(这是一个调试和错误捕获分配。我看不出它有什么问题)

while True:
        try:
                userInputOne = input(int("How much time in hours a week, do you spend practicing? ")
        except TypeError:
                print("Oops! Practice time must be rounded to the nearest integer. It also needs to be a numerical value! ")
                break
    else:
        userInputTwo = str(input"How good to do want to be? Enter 'very good', 'good', mediocre, 'not good' ")
        if userInputTwo not in ('very good', 'good', 'mediocre', 'not good'):
            print("Please use one of the options. ")
        else:
            print("Let's calculate...")
            break

标签: pythonsyntaxexcept

解决方案


我附上了工作代码。语法错误是由缺少括号和错误的缩进引起的。看看你的else:陈述。它与声明的高度不同try:。TypeError 意味着,您不必将输入转换为字符串,因为它们已经是。否则我建议你创建一些变量并int()在你想用它们计算时转换它们。

while True:
    try:
        userInputOne = input("How much time in hours a week, do you spend practicing? ")
    except TypeError:
        print("Oops! Practice time must be rounded to the nearest integer. It also needs to be a numerical value! ")
        break
    else:
        userInputTwo = input("How good to do want to be? Enter 'very good', 'good', mediocre, 'not good' ")
        if userInputTwo not in ('very good', 'good', 'mediocre', 'not good'):
            print("Please use one of the options. ")
        else:
            print("Let's calculate...")
            break

编辑:我建议使用 PyCharm(如果你不这样做),它的自动缩进功能和漂亮的“缩进指南”。所以你可以更容易地看到许多错误。


推荐阅读