尝试在输入中打印字符串和变量时出现语法错误
SyntaxError when trying to print a string and a variable in an input
我的代码应该遍历一系列简单的方程式(例如 1+1 = 2),从答案中拆分方程式,然后向用户询问方程式。我在打印方程式的那一行遇到 SyntaxError,我认为它与变量和 tring 的组合有关,因为它在没有插入变量时运行良好。
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
我在这里错过了什么?
说明:
对不起!犯了一个错误并复制了我的测试代码。重要的一行:
打印(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
更新:
我发现如果我将行更改为:
响应 = 输入(等式 [0])
然后它运行正常,但我需要根据问题陈述在末尾添加一个'='。当我使用 print 时,它会换行。有解决办法吗?
假设您的问题列表类似于以下内容:
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)
已解决:我的 IDE 使用 python 2.7 而不是 3.6,后者需要在同一行中打印字符串和变量。
我的代码应该遍历一系列简单的方程式(例如 1+1 = 2),从答案中拆分方程式,然后向用户询问方程式。我在打印方程式的那一行遇到 SyntaxError,我认为它与变量和 tring 的组合有关,因为它在没有插入变量时运行良好。
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
我在这里错过了什么?
说明: 对不起!犯了一个错误并复制了我的测试代码。重要的一行: 打印(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
更新: 我发现如果我将行更改为: 响应 = 输入(等式 [0]) 然后它运行正常,但我需要根据问题陈述在末尾添加一个'='。当我使用 print 时,它会换行。有解决办法吗?
假设您的问题列表类似于以下内容:
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)
已解决:我的 IDE 使用 python 2.7 而不是 3.6,后者需要在同一行中打印字符串和变量。