Reputation: 23
My code is supposed to loop through a list of simple equations (e.g. 1+1 = 2), split the equations from the answers, and then ask the user the equation. I'm getting a SyntaxError on the line where it prints the equation, and I think it has to do with the combination of the variable and the tring since it runs fine when there is no variable inserted.
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
What am I missing here?
clarifications: SORRY! made a mistake and copied my test code. The important line: print(f'{equation[0]}=') has been corrected.
Indentation is identical to what is posted. equation list looks like:
1+1=2
2+2=4
44-15=29
1x2=2
full traceback:
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
Update: I found that if I change the line to: response = input(equation[0]) then it runs fine, but I need to add an '=' to the end according to the problem statement. When I use print, it puts it on a new line. Is there a workaround for this?
Upvotes: -1
Views: 639
Reputation: 23
Solved: My IDE was using python 2.7 instead of 3.6 which was needed to print a string and a variable in the same line.
Upvotes: 0
Reputation: 3288
Assuming your question list is similar to the following:
questions = ['2 + 2 = 4', '3 - 1 = 2', '2 * 4 = 8']
This is how I would proceed:
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)
Upvotes: 1