Stig
Stig

Reputation: 77

Variables in Python: Add and change variables

I am currently making a game in Python, and now I want to add a store.

I want to do this with a variable. I know how to add variables, and how to change them, but not how to increase or decrease the variable.

I have actually never used variables before. I have read about it, but I don't remember much about it.

def level1():
os.system('cls')
gold = 500
print
print 'You have currently',
print (gold),
print 'gold'
time.sleep(3)
level2()

def level2():
print
print 'Congratulation! You completed the quest! You received 200 gold.'
time.sleep(2)
gold =+ 200
print 'You have now',
print (gold),
print 'gold.'
time.sleep(5)

And the result is:

You have currently 500 gold

Congratulation! You completed the quest! You received 200 gold. You have now 200 gold.

I tried gold + 200, gold += 200, and gold =+ 200, but only the last one worked.

I also tried

print 'You have now' + gold + 'gold'

But that didn't work for some reason. I also tried with

print 'You have now' + (gold) + 'gold'

I am not quite sure what's wrong here, and I would appreciate all the help I can get!

Thank you very much.

EDIT:

I forgot to add a huge part of my question. I am sorry for that!

==================================================================================

In the store, I will sell multiple items to different prices. Not all of the items will be available in the beginning of the game. Therefore I want an item to check how much gold the user have. If the user have under x gold, he can't buy that item.

If the level have reached level 04, that specific item will be unlocked.

Upvotes: 1

Views: 611

Answers (1)

Ayush
Ayush

Reputation: 42440

It should be gold += 200 and not gold =+ 200.

Secondly, it seems gold is a variable that is local to each function, i.e. assigning gold to 500 in level1() does not set it to that value in level2. You need to either pass it in as arguments, or have it as a global.

To pass as arguments:

def level1(gold) :
  # do your stuff here
  level2(gold)

def level2(gold) :
  # do your stuff here

# entry point of your application
if __name__ == "__main__" :
  # initialize `gold` here
  gold = 500
  level1(gold)

To use a global instance:

# global variable 
gold = 500

def level1() :
  # specify that you want to use the global instance of gold
  global gold
  # do your stuff here

def level2() :
  global gold
  # do your stuff here

Upvotes: 2

Related Questions