You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python 3.9.12中f-string语法错误求助:SyntaxError: invalid syntax

乘法表代码f-string语法错误解决办法

我使用Spyder搭配Python 3.9.12编写乘法表代码,但使用f-string时出现SyntaxError: invalid syntax语法错误,尝试用单、双引号包裹f-string内容均无法解决,以下是相关代码及报错信息:

原代码

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}""")

原代码报错信息

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

尝试单引号后的代码

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}'')

对应报错信息

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

问题原因及解决办法

  1. 引号冲突:f-string的外层引号和内部引号不能完全相同,否则Python会提前识别字符串结束位置,导致语法错误。解决方式:
    • 外层用双引号时,内部用单引号;外层用单引号时,内部用双引号,无需转义
    • 或者对内部相同引号进行转义(比如\"或\'),但嵌套不同引号更简洁
  2. 乘法计算错误:循环中的i=user_input是赋值语句,不是乘法计算,应该改为i * user_input

修正后的完整代码

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}")

内容的提问来源于stack exchange,提问作者Justin Henson

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 06:01:07