Home > Enterprise >  How do I add to a variable based on another variables value? (Python)
How do I add to a variable based on another variables value? (Python)

Time:04-03

So I am making a game in Python, and have this bit of code as a function.

def playerDeploySoldiers():
    global error #a basic error, contect the creator message
    answer=1#tells the program when to stop asking
    while(answer==1):
        clearScreen()#just clears the screen
        printDeploySoldiers()
        #needed to define answerDeploySoldiers
        if(answerDeploySoldiers=="1"):
            deploySpot=sanitised_input("Where: ", str, range_=(playerCountries))
            deployNumber=sanitised_input("How many: ", int, 1, playerExtraSoldiers)
        elif(answerDeploySoldiers=="0"):#none of this matters
            print("You have finished deploying soldiers")
            answer=0
        else:
            print(error)

sanitised_input() is just input() but ensuring the player can't add something random like 'asdflasdf;jasdf' as their input. deploySpot will be equal to a country name. For every country, there is a variable called armiesCountryNameHere. deployNumber is a positive integer.

I want to add deployNumber, an integer value, to armiesValueOfdeploySpot (armiesdploySpot =deployNumber), without having to put an if-statement for every possible country deploySpot could be. Is this possible? For example, if deploySpot==USA (not actually an option but just to pretend), I would add the value of deployNumber (which could be something like 100 or 986) to armiesUSA (armiesUSA =deployNumber). But I can't be sure that deploySpot==USA. It could be Mexico, Brazil, Russia, France, (none of these are actual options but they're examples), or any other country.

I have tried finding answers on stackoverflow, but came up with nothing I could understand or ever hope to with the keywords or similar questions I could think of. Most things involved creating a variable using another's value, using a differet language for something different, or something completely beyound my understanding.

For clarification, I am trying to avoid having to do this under deployNumber's value assignment.

if(deployNumber=="USA"):
    armiesUSA =deployNumber

and having to do that for EVERY possible deploySpot value.

CodePudding user response:

Dictionaries in python can be assigned like so:

First_var = 0
Second_var = "hi"
MY_DICT = {First_var:Second_var}
# Reference like so:
Value = MY_DICT[First_var]
#Value now equals Second_var because it assigns the value of the first variable to the next.

I think this is what you are asking? If you mean that you want the value to change based on another variable then add:

CONDITION = True
if(CONDITION):
   MY_DICT[First_var] = NewValue

I believe this should change the value assigned. Tell me if I am wrong

  • Related