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

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

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

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

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

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

完全回溯:

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

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

u59ebvdq

u59ebvdq1#

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

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

我将这样做:

score = 0
for question in questions:
    temp = question.split('=')
    equation = temp[0].strip()
    answer = temp[1].strip()
    resp = input(equation)
    if resp == answer:
        score += 1
print(score)

相关问题