How do I pass variables around in Python?

2024/10/5 19:13:32

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 to be able to pass "weapons" "damage" "p1 n p2" throughout my code. As you can see I have tried using parameters for p1 n p2, but I am a little bit a newbie.


import randomdef main():print("Welcome to fight club!\nYou will be fighting next!\nMake sure you have two people ready to       play!")p1=input("\nEnter player 1's name ")p2=input("Enter player 2's name ")print("Time to get your weapons for round one!\n")round1(p1,p2)def randomweapons(p1,p2):weapon=["Stick","Baseball bat","Golf club","Cricket bat","Knife",]p1weapon=random.choice(weapon)p2weapon=random.choice(weapon)print(p1 +" has found a "+p1weapon)print(p2 +" has found a "+p2weapon)def randomdamage():damage=["17","13","10","18","15"]p1damage=random.choice(damage)p2damage=random.choice(damage)def round1(p1,p2):randomweapons(p1,p2)def round2():pass
def round3():pass
def weaponlocation():passmain()
Answer

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:

class MyGame:          # define the classdef play(self):    # each method gets an instance passed as "self"self.p1 = input("Enter player 1's name ")    # attributes can be assigned on selfself.p2 = input("Enter player 2's name ")self.round1()self.round2()def random_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)def round1(self):print("Lets pick weapons for Round 1")self.random_weapons()def round2(self):print("Lets pick weapons for Round 2")self.random_weapons()def main():game = MyGame()  # create the instancegame.play()      # call the play() method on it, to actually start the game
https://en.xdnf.cn/q/119033.html

Related Q&A

How to compare an item within a list of list in python

I am a newbie to python and just learning things as I do my project and here I have a list of lists which I need to compare between the second and last column and get the output for the one which has t…

Make for loop execute parallely with Pandas columns

Please convert below code to execute parallel, Here Im trying to map nested dictionary with pandas column values. The below code works perfectly but consumes lot of time. Hence looking to parallelize t…

Pre-calculate Excel formulas when exporting data with python?

The code is pulling and then putting the excel formulas and not the calculated data of the formula. xxtab.write(8, 3, "=H9+I9")When this is read in and stored in that separate file, it is sto…

Validating Tkinter Entry Box

I am trying to validate my entry box, that only accepts floats, digits, and operators (+-, %). But my program only accepts numbers not symbols. I think it is a problem with my conditions or Python Rege…

Imaplib with GMail offsets uids

Im querying my gmail inbox using pythons ImapLib with a range parameter, but my returned uids are offset from what I request. My request is as follows:M = imaplib.IMAP4_SSL(imap.gmail.com) M.login(USER…

Accessing a folder containing .wav files [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.This question was caused by a typo or a problem that can no longer be reproduced. While similar q…

What is the right Python idiom for sorting by a single criterion (field or key)? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.Want to improve this question? Update the question so it focuses on one problem only by editing this post.Closed 8…

Incorrect checking of fields in list using a for loop

I have the following code that seeks to read the file contents into a list (this bit works) and then display a message of acceptance, IF the bank details (user and corresponding number) matches. e.g. i…

Why myVar = strings.Fields(scanner.Text()) take much more time than comparable operation in python?

Consider the following code in golangnow := time.Now() sec1 := now.Unix()file, err := os.Open(file_name) if err != nil {log.Fatal(err) } defer file.Close()scanner := bufio.NewScanner(file)var parsedLin…

When reading an excel file in Python can we know which column/field is filtered

I want to capture the field or column name that is filtered in the excel file when reading through python. I saw that we can also capture only the filtered rows by using openpyxl and using hidden == Fa…