Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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}"'
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading