You need to enable JavaScript to run this app. 为什么普通print语句正常运行,f-string版本却出现语法错误?
优惠活动
大模型
产品
解决方案
定价
更多

为什么普通print语句正常运行,f-string版本却出现语法错误?

错误原因
  • f-string引号冲突:你定义f-string时外层用了双引号",内部访问字典键时也用了双引号,Python会把内部的第一个"识别为f-string的结束标记,直接触发语法错误。只要保证f-string外层引号和内部字符串的引号不同即可,比如外层用双引号、内层用单引号。
  • 循环内覆盖牌堆变量:全局定义的cards是整副牌的牌堆,你在for循环中把发牌结果也命名为cards,第一次循环执行后原牌堆就被覆盖为只有2张牌的列表,后续给庄家发牌的逻辑会完全错误,需要修改循环内的临时变量名。
修正后可运行代码
import random

cards = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]

players = ["player", "dealer"]

players_hands = {}
players_scores = {}


for player in players:
    # 修改临时变量名,避免覆盖全局牌堆
    hand_cards = random.choices(cards, k = 2)
    players_hands[player] = hand_cards
    players_scores[player] = sum(hand_cards)
    
print(players_hands["player"])

print(players_scores["player"])
# 内层字符串改用单引号,避免和外层f-string的双引号冲突
print(f"Your cards: {players_hands['player']}, current score: {players_scores['player']}")

print(f"Dealer's first card: {players_hands['dealer'][0]}")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.21 23:54:03