简体   繁体   中英

Change value of variable INSIDE a variable python

I want to change the value of a variable that's inside another variable, this is the code I have so far:

person1tokens = 0
person2tokens = 0
token_price = 5
accounts = ["person1tokens","person2tokens"]

def add_tokens(person,amount):
    if person in accounts:
        cost = amount*token_price
        print("You need to pay %d$" % (cost))
        payment = int(input("Payment? "))
        if payment != cost:
            print("Please enter the right amount next time, nothing changed")
        else:
            --Help here--, change value of a the in the function specified account to <account> += amount
            print("Added " + str(amount) + " tokens to account " + str(person) + ", your current balance is " + str(eval(person)"."))
    else:
        print("fail")

I basically want to change the value of person1tokens(for example) without knowing beforehand that I want to change that value, and I want to change that value where it says --Help here--. But the problem is that it is inside the person variable and I don't know how to get the program to "unpack" it from there. So for example if the user does as follows:

add_tokens("person1tokens",5)
You need to pay 25$
Payment? 25
Added 25 tokens to account person1tokens, your current balance is 25.

Any ideas?

If I'm understanding you correctly here, you want to be able to change the value of either person1tokens or person2tokens without knowing which will be changed beforehand (please correct me if I'm wrong). One way I can think to do this would be using a dictionary rather than storing their values in their own separate variables, and then changing the values based off of that.

accounts = {'person1tokens': 0,
            'person2tokens': 0}

def add_tokens(person, amount):
    if person in accounts:
        cost = amount*5
        payment = int(input("Payment? "))
        if payment != cost:
            print("Please enter the right amount next time, nothing changed")
        else:
            accounts[person] = accounts[person] + cost
            print("Added " + str(amount) + " tokens to account " + str(person) + ", your current balance is " + str(accounts[person]) + ".")
    else:
        return False

This would allow you to have a large amount of people and simply refer to them by name. The one downside to this for you is that you won't be able to refer to the variables, but you can still reference the persons balance by doing accounts['nameofperson']

Hope this helped!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM