我正在学习 python,尽管我已经找到了有关此错误的资源,但当应用于我的案例时,他们的解决方案并不是特别清晰。
这里是:
完整错误:
Traceback (most recent call last):
File "main.py", line 136, in <module>
game()
File "main.py", line 131, in game
dealer_result = dealer()
File "main.py", line 66, in dealer
dvalue = value(dealer_hand)
File "main.py", line 36, in value
value += cards.get(c)
TypeError: unsupported operand type(s) for +=: 'int' and 'NoneType'
上下文:
- 这是一款二十一点游戏。
- game() 是一个围绕整个游戏的函数,每个方面都有完整的函数子集。
- 错误不一致
代码流程: 我有卡片 2 到 A,它们的值在字典中定义。
cards = {
"2": 2,
"3": 3,
"4": 4,
"5": 5,
"6": 6,
"7": 7,
"8": 8,
"9": 9,
"10": 10,
"J": 10,
"Q": 10,
"K": 10,
"A": 11,
}
游戏从定义玩家和庄家手牌的变量开始
player_hand = start()
和
dealer_hand = start()
哪里
def start():
hand = []
hand.extend([random.choice(list(cards)), random.choice(list(cards))])
return hand
在开始时,全局“flag”变量被预先设置为“h”,以允许代码在游戏的主要部分进入循环
首先,我们将使用 value(hand)
函数计算玩家手牌的值(value):
def value(hand):
value = 0
for c in hand:
if c != "A":
value += cards.get(c)
elif c == "A" and value >= 11:
value += 1
else:
value += 11
return value
并将其归因于 p_value 变量。
我认为这就是错误所在,因为手牌是从字典中随机选择的牌,所以在浏览同一字典时怎么可能找不到这样的牌?
玩家阶段:
def main(flag):
p_value = value(player_hand)
if p_value == 21:
result = "blackjack"
else:
while flag == "h":
if p_value == 21:
flag = "s"
elif p_value > 21:
print("Bust")
flag = "s"
if flag != "s":
flag = str(input("[h]it, [s]tay or [q]uit?: "))
if flag == "h":
player_hand.extend(hit())
p_value = value(player_hand)
print("Player: Current value: " + str(p_value) + ". Current hand: " + ', '.join(player_hand))
elif flag == "q":
exit()
result = p_value
return result
然后我使用返回的结果来比较最终玩家结果与最终荷官结果
经销商阶段:
def dealer():
dvalue = value(dealer_hand)
print("Dealer value: " + str(dvalue) + ". Dealer hand: " + ', '.join(dealer_hand))
if dvalue == 21:
result = "blackjack"
else:
while dvalue < 17:
dealer_hand.extend(hit())
dvalue = value(dealer_hand)
print("Dealer value: " + str(dvalue) + ". Dealer hand: " + ', '.join(dealer_hand))
result = dvalue
return result
发生错误的真实场景:
Play again? y/n: y
Player: Current value: 10. Current hand: 2, 8
Dealer: Current hand: ?, 5
[h]it, [s]tay or [q]uit?: s
Dealer value: 7. Dealer hand: 2, 5
Traceback (most recent call last):
File "main.py", line 136, in <module>
game()
File "main.py", line 131, in game
dealer_result = dealer()
File "main.py", line 66, in dealer
dvalue = value(dealer_hand)
File "main.py", line 36, in value
value += cards.get(c)
TypeError: unsupported operand type(s) for +=: 'int' and 'NoneType'
预期结果是庄家继续循环执行 hit() 函数,直到他的手牌值 value(dealer_hand)
等于或大于 17。
最佳答案
extend
接受一个“iterable”并将该 iterable 中的所有元素添加到列表中。字符串是一种可迭代对象,并且您的值之一具有多个字符。
另一方面,append
接受一个值并将其按原样添加到列表中。
换句话说:extend
用于从另一个事物集合中添加零个或多个元素; append
用于添加一个元素。
此示例说明了问题所在:
>>> a = []
>>> a.extend("10")
>>> a
['1', '0']
>>> b = []
>>> b.extend(["10"])
>>> b
['10']
>>> c = []
>>> c.append("10")
>>> c
['10']
关于Python: += 不支持的操作数类型: 'int' 和 'NoneType,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75689101/