尝试在输入中打印字符串和变量时出现语法错误

f45qwnt8  于 2021-09-08  发布在  Java
关注(0)|答案(1)|浏览(384)

我的代码应该循环浏览一系列简单的方程式(例如,1+1=2),将方程式从答案中分离出来,然后向用户询问方程式。我在打印方程的那一行得到了一个syntaxerror,我认为它与变量和字符串的组合有关,因为在没有插入变量的情况下,它运行良好。

  1. for question in questions: #iterate through each of the questions
  2. equation = question.split('=') #split the equations into a question and an answer
  3. temp = str(equation[0])
  4. print(f'{equation[0]}=')
  5. answer = input() #Prompt user for answer to equation
  6. if answer == int(equation[1]): #Compare user answer to real answer
  7. score +=1 #If answer correct, increase score

我错过了什么?
澄清:对不起!犯了一个错误并复制了我的测试代码。重要的一行:print(f'{等式[0]}=')已更正。
缩进与张贴的内容相同。方程式列表如下所示:

  1. 1+1=2
  2. 2+2=4
  3. 44-15=29
  4. 1x2=2

完全回溯:

  1. Traceback (most recent call last):
  2. File "<input>", line 1, in <module>
  3. File "C:\Program Files\JetBrains\PyCharm Community Edition 2019.1.1\helpers\pydev\_pydev_bundle\pydev_umd.py", line 197, in runfile
  4. pydev_imports.execfile(filename, global_vars, local_vars) # execute the script
  5. File "C:/Users/nsuess/PycharmProjects/Quiz/exercise.py", line 28
  6. answer = input(f'{equation[0]}=') #Prompt user for answer to equation
  7. ^
  8. SyntaxError: invalid syntax

更新:我发现如果我将行更改为:response=input(等式[0]),那么它运行良好,但是我需要根据问题陈述在末尾添加一个“=”。当我使用print时,它会将其放在新的行上。有解决办法吗?

u59ebvdq

u59ebvdq1#

假设您的问题列表与以下类似:

  1. questions = ['2 + 2 = 4', '3 - 1 = 2', '2 * 4 = 8']

我将这样做:

  1. score = 0
  2. for question in questions:
  3. temp = question.split('=')
  4. equation = temp[0].strip()
  5. answer = temp[1].strip()
  6. resp = input(equation)
  7. if resp == answer:
  8. score += 1
  9. print(score)

相关问题