Python中全局语句的替代方法

2024-04-26 04:12:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我在写一个非常简单的轮盘赌模拟器,只关注红/黑投注(基本上就像一个正面或反面的游戏)。在

我遇到的问题是跨函数调用变量。在

下面是代码(我确定它也有其他问题,但我现在主要关注这个问题):

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来避免这个问题,但我不想求助于此。除了通过使用global之外,如何使用roulette_sim中的用户分配给它的值来调用这个变量?在

我想同样的问题也适用于money变量。在

我目前对Python已经有了非常基本的了解,因此对于任何错误我深表歉意。在

谢谢


Tags: ortoyouinputrawdefredsim
3条回答

您可以将值作为参数传递给函数,并使函数返回更新的值,例如:

def roulette_sim(money, losses):
    print "How much do you want to bet?"
    bet = int(raw_input("> "))   
    if bet > money:
        return bet_too_much(money, losses)
    else:
        eturn red_or_black(money, losses, bet)

其中red_or_black不是修改全局moneylosses变量,而是将丢失的moey量传递给replay,后者用更新后的值调用roulette_sim。在

或者,您可以简单地将所有内容放入一个类中,并使用self.moneyself.losses和{}作为“globals”。在

但是您可能会注意到,这些函数的整个设计都很糟糕。 他们有复杂的关系,他们使用递归,这意味着在(可能少于)1000次下注后,你将得到一个RuntimError: Maximum recursion depth exceeded。在

您可以重构整个代码以使用循环。 只是想说:

^{pr2}$

注意:假设您想编写一个不同的游戏,玩家在其中下注。 使用你的设计,在这个新游戏中重复使用这些功能是非常困难的。在

通过上面的设计,你可以自由地重复使用get_bet()函数来要求玩家下注等。 这只是为了给我们另一个使用循环而不是使用递归循环的紧密耦合函数的原因。在

使用类:

import random

class RouletteSim(object):
    def __init__(self):
        # Defines initial amounts of money and losses
        self.money = 50
        self.losses = 0

    # Starts the sim
    def roulette_sim(self):
        print "How much do you want to bet?"
        bet = int(raw_input("> "))
        if bet > self.money:
            self.bet_too_much()
        else:
            self.red_or_black(bet)

    # Prevents one from betting more money than one has
    def bet_too_much(self):
        print "You do not have all that money. Please bet again."
        raw_input("Press ENTER to continue> ")
        self.roulette_sim()

    # Asks user to select red or black, starts the sim, modifies money/losses
    def red_or_black(self, bet):
        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!"
            self.money += bet
            print "You now have %r money" % (self.money)
            print "Your losses are %r" % (self.losses)
            self.replay()
        elif number == 2 and answer == "black":
            print "You win!"
            self.money += bet
            print "You now have %r money" % (self.money)
            print "Your losses are %r" % (self.losses)
            self.replay()
        else:
            print "You lost!"
            self.money -= bet
            self.losses += bet
            print "You now have %r money" % (self.money)
            print "Your losses are %r" % (self.losses)
            self.replay()

    # Asks user whether he/she wants to play again
    def replay(self):
        print "Do you want to play again?"
        play_again = raw_input("y/n> ")
        if play_again == "y":
            self.roulette_sim()
        else:
            print "OK, bye loser!"

RouletteSim().roulette_sim()

赌是轮盘赌的有效变量 但在red_或_black函数中,您从

print "OK, you bet %r" %  (bet)

然后呢

^{pr2}$

等等无效,你应该把你的赌注作为参数传给红蓝或黑 按如下方式调用该函数:

red_or_black(bet)   # bet is argument

并将其定义为:

def red_or_black(bet):   # bet is parameter

一切都会好起来的

相关问题 更多 >