简体   繁体   中英

How to overwrite variable in python in a function

def Change_char_stats():
    Char_dmg = 50
    Char_health = 100
    Char_stat_choice= ''
    print('Current Damage is:',Char_dmg,'and health is:',Char_health,'.')
    Char_stat_choice=input('\nWhat character stat would you like to edit?')

    if Char_stat_choice == '1':
        print('Current damage is',Char_dmg,'.')
        Char_dmg=int(input('Character damage to: '))
        print('Character damage has been changed to',Char_dmg,'.')
        Change_char_stats()

    elif Char_stat_choice == '2':
        print('Current damage is',Char_health,'.')
        Char_health=int(input('Character health to: '))
        print('Character health has been changed to',Char_health,'.')
        Change_char_stats()
    else:
        print('Input invalid.')
        Change_char_stats()

Change_char_stats()

So basically I'm working on a simple game for myself on Python, and I'm having an issue with my variables as when I run the program original variables are set to 50 dmg and 100 health, but what I want to do is be able to run the code, change the variables and then have them stay as that. Although I understand why the variables aren't staying as the new values, I have no clue how to over-write them, help would be much appreciated.

Thanks.

I suggest creating a class to package all of the variables into a single object:

def class player_character:
    def __init__(self):
        self.health = 100
        self.dmg = 50

Now you create an instance of the class:

player = player_character()

And change the variables directly:

player.health -= 10

Alternatively, you can add functions to the class:

def class player_character:
    def __init__(self):
        self.health = 100
        self.dmg = 50

    def hit(self, dmg):
        self.health -= dmg

Now you can call the function on an object:

player.hit(10)

Classes are incredibly powerful and great tools for organizing code. They allow you to treat a lot of data as a single entity. I strongly encourage you to learn more about them and object oriented programming in general.

Place the variables outside function body and make them accessible within usng global keyword:

somevar = 5

def foobar(x):
    global somevar
    somevar = x

print somevar
foobar(6)
print somevar

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