为什么我的基本打印语句可以工作,但我的 f-string 版本会产生语法错误?
Why does my basic print statement work, but my f-string version produces a syntax error?
学习的早期阶段 Python,并试图完成 100 天的代码挑战。正在构建一个粗略的二十一点游戏,但我确信我无法识别可能是一个非常简单的修复方法!
到目前为止,这是我的代码:
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:
cards = random.choices(cards, k = 2)
players_hands[player] = cards
players_scores[player] = sum(cards)
print(players_hands["player"])
print(players_scores["player"])
print(f"Your cards: {players_hands["player"]}, current score: {players_scores["player"]}")
print(f"Dealer's first card: {players_hands["dealer"][0]}")**
我想打印 f-string 版本而不是基本的 print 语句,但一直出现语法错误并且不知道我做错了什么。
您应该检查您是否至少使用 Python 3.6,其中引入了 f-strings,而且...
您正在使用双引号访问字典,这与对字符串使用双引号有冲突。尝试更改为
print(f"Dealer's first card: {players_hands['dealer'][0]}")
或
print(f'Dealer\'s first card: {players_hands["dealer"][0]}')
学习的早期阶段 Python,并试图完成 100 天的代码挑战。正在构建一个粗略的二十一点游戏,但我确信我无法识别可能是一个非常简单的修复方法!
到目前为止,这是我的代码:
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:
cards = random.choices(cards, k = 2)
players_hands[player] = cards
players_scores[player] = sum(cards)
print(players_hands["player"])
print(players_scores["player"])
print(f"Your cards: {players_hands["player"]}, current score: {players_scores["player"]}")
print(f"Dealer's first card: {players_hands["dealer"][0]}")**
我想打印 f-string 版本而不是基本的 print 语句,但一直出现语法错误并且不知道我做错了什么。
您应该检查您是否至少使用 Python 3.6,其中引入了 f-strings,而且...
您正在使用双引号访问字典,这与对字符串使用双引号有冲突。尝试更改为
print(f"Dealer's first card: {players_hands['dealer'][0]}")
或
print(f'Dealer\'s first card: {players_hands["dealer"][0]}')