我目前正在使用python 2.7编写二十一点游戏。作为应用程序游戏流程的一部分,我定义了一个名为player_turn()
的新功能,在该功能中,我需要用户输入,根据输入,该输入将导致不同的情况(“命中”将给玩家另一张牌,然后“按住“会终止玩家的回合,并将其传递给发牌人。否则会导致自定义错误)
def player_turn():
if sum(player_card_numbers) < 21:
user_decision = input('would you like to hit or hold?')
if user_decision == 'hit':
player_cards.append(deck.draw())
print player_cards, dealer_cards
player_turn()
elif user_decision == 'hold':
print "Dealer's turn!"
dealer_turn()
else:
print "player must choose 'hit' or 'hold'"
player_turn()
elif sum(player_card_numbers) == 21:
print "Blackjack!"
dealer_turn()
else:
print "Player Burnt! \nDealer's turn!"
dealer_turn()
值得一提的是,该代码最初是用python 3.7编写的,后来又进行了更改。该代码与3.7完美兼容。
现在我收到此错误:
NameError: name 'hit' is not defined
我希望获得一些有关如何解决此问题的建议,以及有关为什么会发生这种情况的解释。 :)
答案 0 :(得分:0)
问题是这一行:
user_decision = input('would you like to hit or hold?')
在Python2中,input()
具有eval()
的性质,因此它在逃避您的答案:点击
>>> user_decision = input('would you like to hit or hold?')
would you like to hit or hold?hit
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 1, in <module>
NameError: name 'hit' is not defined
>>>
Python 2的编码标准是不使用input()
而是使用raw_input()
:
>>> user_decision = raw_input('would you like to hit or hold?')
would you like to hit or hold?hit
>>> user_decision
'hit'
>>>
在Python 3中,input()
函数与Python 2中的raw_input()
等效。