0

I keep receiving SyntaxError message on ex41.py OR oop_test.py, and I've run through the whole script, everything is exactly as it is in the book, but I keep getting this - the variable {answer} is seemingly only defined in the try: section, so I have no clue why I am getting this SyntaxError.

***:hardway ***$ python ex41.py english File "ex41.py", line 76 print(f"ANSWER: {answer}\n\n") ^ SyntaxError: invalid syntax

Here is the try: section, where the variable is at:

try:
    while True:
        snippets = list(PHRASES.keys())
        random.shuffle(snippets)

        for snippet in snippets:
            phrase = PHRASES[snippet]
            question, answer = convert(snippet, phrase)
            if PHRASE_FIRST:
                question, answer = answer, question

            print(question)

            input("> ")
            print(f"ANSWER: {answer}\n\n")

except EOFError:
    print("\nBye") `

The entirety of the code can be found here: Learning Python The hard way Ex. 41 - Learning to Speak Object-Oriented

1 Answers1

0

Your code looks fine. The problem is the Python version you are running.

As mentioned in the comments above f strings were first introduced in Python 3.6 (see official documentation). If you want to use this feature you need to update to Python 3.6.

If you do not (or cannot) switch version you can use format() instead:

  print("ANSWER: {}\n\n".format(answer))

OR use the old style %s (formatting string) operator:

  print("ANSWER: %s\n\n" %answer)

See: What does %s mean in Python?

I would suggest format() over the second method though.

If you are making code that will be run on Python versions before Python 3.6 it it a good idea to use the alternatives listed above.

Xantium
  • 11,201
  • 10
  • 62
  • 89
  • haha, I'm pretty novice, and this definitely worked...lesson learned. – Sam Parsons Mar 14 '18 at 18:29
  • @SamParsons Since you are still learning Python, can I suggest you update to Python 3.6 (or the latest version) so that you get all the newest features, but if you can't never mind... – Xantium Mar 14 '18 at 18:31