Python 3.9.12: f-string error – SyntaxError: invalid syntax

Question:

I am using Spyder with Python 3.9.12

Here is the code I have inside Spyder:

user_input = (input('Please enter a number between 1 and 12:>>' ))

while (not user_input.isdigit()) or (int(user_input) < 1 or int(user_input) > 12):
    print('Must be an integer between 1 and 12')
    user_input = input('Please make a selection:>> ')
user_input = int(user_input)
print('============================')
print()
print(f"This is the "{user_input}" times table")
print()
for i in range(1,13):
    print(f""{i}" x "{user_input}" = "{i=user_input}"")

Error output from Spyder:

runfile('/Users/user/spyder-files/For-Loops.py', wdir='/Users/user/spyder-files')
  File "<unknown>", line 49
    print(f""This is the "{user_input}" times table"")
             ^
SyntaxError: invalid syntax

I tried using single quotes but get the same error message:

user_input = (input('Please enter a number between 1 and 12:>>' ))

while (not user_input.isdigit()) or (int(user_input) < 1 or int(user_input) > 12):
    print('Must be an integer between 1 and 12')
    user_input = input('Please make a selection:>> ')
user_input = int(user_input)
print('============================')
print()
print(f'This is the '{user_input}' times table')
print()
for i in range(1,13):
    print(f''{i}' x '{user_input}' = '{i=user_input}'')

Same error:

runfile('/Users/user/spyder-files/For-Loops.py', wdir='/Users/user/spyder-files')
  File "<unknown>", line 49
    print(f'This is the '{user_input}' times table')
                         ^
SyntaxError: invalid syntax

I appreciate any suggestions.

Thanks.

Asked By: Justin Henson

||

Answers:

You used double quotes in f""{i}" x "{user_input}" = "{i=user_input}"". Now the string starts at the first double quote and ends at the second. The following text now leads to a SyntaxError.

You could use triple quotes to define the string. The fourth is now part of the strings content.

f""""{i}" x "{user_input}" = "{i*user_input}""""

Or use different quotes

f'"{i}" x "{user_input}" = "{i=user_input}"'
Answered By: Matthias