try:/except:尝试运行modu时返回Python中的语法错误

2024-06-25 06:07:58 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

Tags: thetoininputtime错误notbe
2条回答

我附上了工作代码。 语法错误是由于缺少排列和错误的缩进造成的。看看你的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(如果你不这样做的话)的自动缩进功能和不错的“缩进准则”。所以你可以更容易地看到许多错误

您的代码:

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

首先,应该如下所示:

while True:
    try:
        userInputOne = input(int("How much time in hours a week, do you spend practicing? "))
    except TypeError:
        ...
        ...

我喜欢用一些方法来解决这个问题:

  • 对文件运行pylint。它将告诉您哪里存在错误,并为您提供可以改进的代码警告
  • 使用vim和命令==,它将尝试执行一些自动缩进

但最重要的是要理解whitespace is important in Python。整个文件中都存在空格语法错误。代码中需要有四个空格而不是八个空格。另外,正如上面的注释所指出的,您有一些不平衡的括号,这将破坏您的代码。此外,还有一个else语句,没有if。周围有很多问题,所以我建议一次重新编写几行代码,并在继续之前确保它正常工作。此外,不能将字符串转换为int,否则至少会得到意外的结果

相关问题 更多 >