注释中的python无效语法

Posted

技术标签:

【中文标题】注释中的python无效语法【英文标题】:python invalid syntax in comment 【发布时间】:2016-01-21 20:35:39 【问题描述】:

使用空闲 Python 3.4.3。这是一个脚本,它给用户一个小测验,然后计算有多少是正确的。在我的脚本运行之前,我的评论中有一个无效的语法错误。这是评论周围的整个代码。具体注释在score = decimal.Decimal(score)这一行下:

score = amountright/7*100 """this takes the amount of questions the user got right, divides it by 7 (the total number of questions), then multiplies it by 100 to get a percentage correct and stores it in the variable score"""
import decimal """this will import a function to round off the final percentage to a whole number instead of an unnecessarily long decimal"""
score = decimal.Decimal(score)
"""this redefines the score variable as some sort of roundable decimal. the round() function in the line below will still function without this line, but it would print an unneeded .0 before the %"""
print ("You got " + str(amountright) + " out of 7 right, or " + str(round(score,0)) + "%.")
"""the round() function works by rounding the first argument to n places in the second argument"""

我运行它,得到无效的语法错误,然后它突出显示单词score red 中的 s 和 c。使用 ' 对此没有任何影响。但是,当我像这样运行代码时:

"""
This redefines the score variable as some sort of roundable decimal. the round() function in the line
below will still function without this line, but it would print an unneeded .0 before the %
"""

它仍然给出语法错误,但这次只突出显示score红色中的s。 应 unutbu 的要求添加的 repr:

print ("Here is a quiz!\n") #starting prompt

useranswer = input("Question 1: What is 4+|6x1|? ")
#this is where the user enters their answer to the question

#the following 2 variables on lines 7 and 9 only need to be defined once
rightanswerresult = "Correct! Next question:\n" #tells the user they are correct
invalidanswerresult = "This is not a number. This is counted as a wrong answer.\n"
"""if the user does not answer with a number, this string will print telling them so and the question will
be counted wrong"""

amountright = 0 #this number increases every time the user answers a question correctly

if useranswer.isdigit(): #if the user's answer is a number, the code below runs
    if useranswer == "10":
    #this checks if the user's answer and the correct answer are the same, then runs the code below if they are"""
        print (rightanswerresult) #this prints the variable rightanswerresult described on line 7
        amountright += 1 #this will add the value one to the variable amountright described on line 13
    else: #if the user's answer and the correct answer are not the same, the code below runs
        print ("Wrong, it was 10. Next question:\n") #tells the user they were wrong
else: #if the user's answer is NOT a number, this runs
    print (invalidanswerresult) #this prints the varible invalidanswerresult described in line 9
#this pattern is repeated 5 more times. an altered process is used for the True/False question (#7)
useranswer = input("Question 2: What is (15/3) x 12? ")
if useranswer.isdigit():
    if useranswer == "60":
        print (rightanswerresult)
        amountright += 1
    else:
        print ("Wrong, it was 60. Next question:\n")
else:
    print (invalidanswerresult)

useranswer = input("Question 3: What is 20+24/12? ")
if useranswer.isdigit():
    if useranswer == "22":
        print (rightanswerresult)
        amountright += 1
    else:
        print ("Wrong, it was 22. Next question:\n")
else:
    print (invalidanswerresult)

useranswer = input("Question 4: Solve for x: 2x-1=5 ")
if useranswer.isdigit():
    if useranswer == "3":
        print (rightanswerresult)
        amountright += 1
    else:
        print ("Wrong, it was 3. Next question:\n")
else:
    print (invalidanswerresult)

useranswer = input("Question 5: What is the square root of 256? ")
if useranswer.isdigit():
    if useranswer == "16":
        print (rightanswerresult)
        amountright += 1
    else:
        print ("Wrong, it was 16. Next question:\n")
else:
    print (invalidanswerresult)

useranswer = input("Question 6: What is 7x7+7/7-7? ")
if useranswer.isdigit():
    if useranswer == "1":
        print (rightanswerresult)
        amountright += 1
    else:
        print ("Wrong, it was 1. Next question:\n")
else:
    print (invalidanswerresult)
#the question below appears different because it is True/False and the last question
useranswer = input("Question 7: True or False: |3|=98/2 ").lower() #as before, the user is asked a question
if useranswer == "false": #checks if user's answer is false, and runs code below if it is
    print ("You're right! Your results are below:\n") #this tells the user they are correct then shows them their final score
    amountright += 1 #as before, this will add the value one to the variable amountright described on line 8
if useranswer == "true": #checks if user's answer is true, and runs code below if it is
    print ("Actually, its false. Your results are below:\n") #this tells the user they are wrong then shows them their final score
elif useranswer != "false" and useranswer != "true": #if the user's answer is not true or false, this code runs
    print ("It seem you didn't enter true or false. Maybe you made a spelling error? Anyways, your results are below:\n")
    """tells user their answer is invalid then shows final score"""
#all questions have been completed. below is the final score calculation
score = amountright/7*100 """this takes the amount of questions the user got right, divides it by 7
(the total number of questions), then multiplies it by 100 to get a percentage correct and stores
it in the variable score"""
import decimal """this will import a function to round off the final percentage to a whole number
instead of an unnecessarily long decimal"""
score = decimal.Decimal(score)
"""this redefines the score variable as some sort of roundable decimal. the round() function in the line
below will still function without this line, but it would print an unneeded .0 before the %"""
print ("You got " + str(amountright) + " out of 7 right, or " + str(round(score,0)) + "%.")
"""the round() function works by rounding the first argument to n places in the second argument"""

评论有错误吗?

【问题讨论】:

我无法重现这个。 文件中可能有一些隐藏的(不可打印的?)字符。将脚本保存到文件中可能会有所帮助,例如 script.py,然后打开文件:f = open('script.py', 'rb') 并查看内容的 reprprint(repr(f.read()))。如果您发布repr,我们或许可以为您提供更多帮助。 你确定这个错误是关于评论的吗?你的代码是什么?或者尝试删除这些评论然后运行您的代码? 我也无法重现这个... @MorganThrapp 我也是。在新文件中工作正常 【参考方案1】:

# 用于表示comment 的开始。三引号用于表示multiline strings 的开始和结束。虽然字符串不是 cmets,但有时 multiline strings can be used as multiline comments。

但是,字符串的放置还是要遵守Python syntax rules。

score = amountright/7*100 """this takes the amount..."""

引发 SyntaxError,因为该字符串遵循一个不是字符串的表达式。 amountright/7*100 """this takes the amount...""" 大致相当于

>>> 1 "foo"
SyntaxError: invalid syntax

Python 不知道如何计算一个数字后跟一个字符串。即使它可以被评估,它的值也会是assigned to score。多行字符串不会被解释为注释。要使多行字符串充当注释,它必须单独位于一行:

score = amountright/7*100 
"""this takes the amount of questions the user got right, divides it by 7
(the total number of questions), then multiplies it by 100 to get a percentage correct and stores it in the variable score"""

import decimal 
"""this will import a function to round off the final percentage to a whole number
instead of an unnecessarily long decimal"""

或者,使用更常用的注释语法:

score = amountright/7*100 
# this takes the amount of questions the user got right, divides it by 7 (the
# total number of questions), then multiplies it by 100 to get a percentage
# correct and stores it in the variable score

在每一行前面加上一个# 可能看起来很痛苦,但这是一个很好的文本 用 Python 编程的编辑器应该有一种方法让您选择文本区域和 按下按钮或组合键为您插入# 标志。如果你的 编辑器没有这个功能,find one that does。

【讨论】:

我尝试用#s 将评论放在两行中。仍然出现语法错误,但没有突出显示的部分,并且 idle 将光标放在十进制单词中的 i 和 m 之间。闲置只是……不好吗? 好吧,不要问我为什么,但是在将我所有的其他 """ cmets 更改为 # 之后,脚本运行良好 @dioretsa:IDLE 使用内置的 compile 函数编译 Python 代码。 compile 函数引发 SyntaxErrors。 IDLE 编辑器与交互式控制台 python 的唯一不同之处是在 SyntaxError 的属性中指示的位置用行中的光标(和红色突出显示)而不是下方行上的插入符号(移位 6)来标记。【参考方案2】:

我遇到了类似的问题: 有时 IDLE 会指出错误的方向并在错误的位置出现错误的字符时说“无效语法”,例如

print(f"value of counter = counter")

在第 50 行中效果很好,但是

print(f"value of counter = counter]")

在第 1 行产生指向不相关注释的消息“无效语法”

我花了一些时间在格式化字符串中找到错字“]”。 所以要经常检查你的牙套!

【讨论】:

如果您在注释之前缺少右括号,python 将注释的结尾(或之后的下一件事)指示为错误而不是之前的行,这也是可能的。跨度>

以上是关于注释中的python无效语法的主要内容,如果未能解决你的问题,请参考以下文章

Python中的gsutil引发语法错误

Python 2 中 Python 3 的 str.split 的无效语法错误

python 3.5代码中的变量需要类型注释

无效的语法错误:使用 Python 和 Spark 构建决策树、流失预测

python基本语法规则都有哪些?

【Python基础】python基本语法规则都有哪些?