Home > Net >  How to make a variable constantly update with python
How to make a variable constantly update with python

Time:10-19

I am trying to make a clicker-based game with python and I'm trying to make an upgrade.

def silvercoinX():
   global x
   x=1
   return x
x = silvercoinX()
def silvercoinYUpdate():
   y=10
   y  = round(y*1.33)
   return y
y = silvercoinYUpdate()
silvercoinYUpdate()
print(round(y))
silvercoinYUpdate()
print(round(y))
silvercoinYUpdate()
print(round(y))

Output

23

23

23

I'm trying to make the output

23

31 # (this being 23*1.33)

41 # (this being 31*1.33)

The X is going to be how much you get when you click

CodePudding user response:

Beware this is constant

def silvercoinYUpdate():
   y=10
   y  = round(y*1.33)
   return y
# same as
def silvercoinYUpdate():
   y = 10  # you reset it here
   y = 10   round(10*1.33)
   y = 10   round(13.3)
   y = 23
   return 23

You maybe want something like this:

def silvercoinYUpdate(y=10):
   y  = round(y*1.33)
   return y
y = silvercoinYUpdate() # 23
y = silvercoinYUpdate(y) # 31

or

y=10
def silvercoinYUpdate():
   global y
   y  = round(y*1.33)
   return y
silvercoinYUpdate() # 23
silvercoinYUpdate() # 31

CodePudding user response:

Hi and welcome to stackoverflow.

First of all, you are printing all the y values, not sure if that is what you meant to do. Since, you are calling function silvercoinYUpdate() three times, all that function is doing is adding 10 with round(10*1.33) which gives you 23 everytime you print it.

It looks like you do not even need x here if you want to return

23
31
41

Just declare y outside the function silvercoinYUpdate() .

    y = 10
    def silvercoinYUpdate():
       global y
       if y <= 10:
          y  = round(y * 1.33)
       else:
          y = round(y*1.33)
       return y
    silvercoinYUpdate()
    print(y)
    silvercoinYUpdate()
    print(y)
    silvercoinYUpdate()
    print(y)

If you do not use if else statement, you will get your output as:

23
54

and so on. I am assuming you are going to use 10 as your initial value. Otherwise set your if-else statement accordingly.

Hope this helps!

  • Related