我正在编写一个非常简单的轮盘赌模拟器,只专注于红/黑投注(基本上就像正面或反面的游戏)。
我遇到的问题是跨函数调用变量。
这是代码(我确定它也有其他问题,但我现在专注于这个问题):
import random
# Defines initial amounts of money and losses
money = 50
losses = 0
# Starts the sim
def roulette_sim():
print "How much do you want to bet?"
bet = int(raw_input("> "))
if bet > money:
bet_too_much()
else:
red_or_black()
# Prevents one from betting more money than one has
def bet_too_much():
print "You do not have all that money. Please bet again."
raw_input("Press ENTER to continue> ")
roulette_sim()
# Asks user to select red or black, starts the sim, modifies money/losses
def red_or_black():
print "OK, you bet %r" % (bet)
print "Red or black?"
answer = raw_input("> ")
number = random.randint(1, 2)
if number == 1 and answer == "red":
print "You win!"
money += bet
print "You now have %r money" % (money)
print "Your losses are %r" % (losses)
replay()
elif number == 2 and answer == "black":
print "You win!"
money += bet
print "You now have %r money" % (money)
print "Your losses are %r" % (losses)
replay()
else:
print "You lost!"
money -= bet
losses += bet
print "You now have %r money" % (money)
print "Your losses are %r" % (losses)
replay()
# Asks user whether he/she wants to play again
def replay():
print "Do you want to play again?"
play_again = raw_input("y/n> ")
if play_again == "y":
roulette_sim()
else:
print "OK, bye loser!"
roulette_sim()
所以,我得到NameError: global name 'bet' is not defined
了,我可以通过使用来避免global
,但我宁愿不诉诸于此。roulette_sim
除了通过 using 之外,我如何在其他函数中调用这个变量,以及用户分配给它的值global
?
我想同样的问题也适用于money
变量。
我目前对 Python 有非常基本的了解,因此对于任何错误,我深表歉意。
谢谢