if 语法无效

Invalid syntax with if

这是一个非常简单的想法,您输入您的测试分数,如果您的分数超过 70% (35/50),您可以对 1 pt 进行更正,基本上给您 100%。如果低于 70%,您可以进行 1/2 个点的修正。

这给了我一个无效的语法并将光标放在最后一个 " 和 ) 之间

score = input("How many problems did you get right on the test?")
maxscore = 50
passscore = 35
wrong = (maxscore - score)

if (score > passscore):
    print ("You will get a 100%")


if (score < passscore):
    print("You can get"(wrong)"% back  with text corrections")

我的编程很糟糕,如果我在这里看起来真的很愚蠢,我很抱歉。

您可以使用逗号分隔多个参数..

print "You can get", wrong, "% back  with text corrections"

在担心语法错误之前,您需要将 wrong 转换为 int 因为 input() returns 用户输入为 str 类型.

score = int(input("How many problems did you get right on the test?"))

如果您不这样做并且用户输入了一个字符串,表达式:

wrong = (maxscore - score) 

将引发 TypeError,这实际上意味着您不能从 int 类型的值(maxscore)中减去 str 类型的值(分数)。


至于你的语法错误。

print("You can get"(wrong)"% back  with text corrections")

语法无效。您需要通过在 print() 调用中使用 str() 转换它来将 wrong 作为字符串包含在内:

print("You can get" + str(wrong) + "% back  with text corrections")

你可以看到,不同类型之间的转换,取决于操作,在你掌握它们之前可能会一团糟。

如果你想连接一个字符串,你需要在变量名和字符串之间添加+。将您的第二个打印行替换为:

print("You can get " + str(wrong) + "% back  with text corrections")

问题出在这里:

print("You can get"(wrong)"% back  with text corrections")

这不是将变量插入字符串的正确方法。您有多种选择:

print("You can get " + str(wrong) + "% back with text corrections")

或者:

print("You can get %d%% back with text corrections" % wrong)

或者:

print("You can get {}% back with text corrections".format(wrong))

或者:

print("You can get ", wrong, "% back with text corrections", sep='')

此外,如果您使用的是 Python 3,则需要执行 score = int(input(... 将收到的字符串转换为整数。

  1. 首先,score必须是int。所以你需要使用 int() 函数来做到这一点。
  2. 并且if不需要(),只需删除它们。
  3. 那么,问题是关于print("You can get"(wrong)"% back with text corrections"),你应该在这里使用+,.format()等。并记住使用 str() 将其转换为字符串。

score = int(input("How many problems did you get right on the test?"))
maxscore = 50
passscore = 35
wrong = (maxscore - score)

if score > passscore:
    print("You will get a 100%")


if score < passscore:
    print("You can get "+str(wrong)+"% back with text corrections")

这是最简单的方法,但是使用.format()会更清晰:

print("You can get {0}% back  with text corrections".format(wrong)) 

或者像这样:

print("You can get {wrong}% back  with text corrections".format(wrong=wrong)) 

每个人都必须从某个地方开始(我对 Python 自己还是很陌生)!

您的第一个问题是您需要将 score 定义为 int:

score = int(input("How many problems did you get right on the test?"))

那么至少有两种解决方案可以修复最后一行代码。一种是使用 + 分隔你的文本字符串,加上 strwrong 转换为字符串格式:

print("You can get " + str(wrong) + "% back  with text corrections")

或者你可以使用.format的方法,更"Pythonic":

print("You can get {0}% back  with text corrections".format(wrong))