Skip to content Skip to sidebar Skip to footer

How Do I Pass Variables Around In Python?

I want to make a text-based fighting game, but in order to do so I need to use several functions and pass values around such as damage, weapons, and health. Please allow this code

Solution 1:

There are a few options.

One is to pass the values as parameters and return values from your various functions. You're already doing this with the names of the two players, which are passed as parameters from main to round1 and from there on to randomweapons. You just need to decide what else needs to be passed around.

When the information needs to flow the other direction (from a called function back to the caller), use return. For instance, you might have randomweapons return the weapons it chose to whatever function calls it (with return p1weapon, p2weapon). You could then save the weapons in the calling function by assigning the function's return value to a variable or multiple variables, using Python's tuple-unpacking syntax: w1, w2 = randomweapons(p1, p2). The calling function could do whatever it wants with those variables from then on (including passing them to other functions).

Another, probably better approach is to use object oriented programming. If your functions are methods defined in some class (e.g. MyGame), you can save various pieces of data as attributes on an instance of the class. The methods get the instance passed in automatically as the first parameter, which is conventionally named self. Here's a somewhat crude example of what that could be like:

classMyGame:          # define the classdefplay(self):    # each method gets an instance passed as "self"
        self.p1 = input("Enter player 1's name ")    # attributes can be assigned on self
        self.p2 = input("Enter player 2's name ")
        self.round1()
        self.round2()

    defrandom_weapons(self):
        weapons = ["Stick", "Baseball bat", "Golf club", "Cricket bat", "Knife"]
        self.w1 = random.choice(weapons)
        self.w2 = random.choice(weapons)
        print(self.p1 + " has found a " + self.w1) # and looked up again in other methodsprint(self.p2 + " has found a " + self.w2)

    defround1(self):
        print("Lets pick weapons for Round 1")
        self.random_weapons()

    defround2(self):
        print("Lets pick weapons for Round 2")
        self.random_weapons()

defmain():
    game = MyGame()  # create the instance
    game.play()      # call the play() method on it, to actually start the game

Post a Comment for "How Do I Pass Variables Around In Python?"