0

Ive tried to change the value of storage but that did not work, after the while loop is done, the value is set back to its original value instead of being at 100.

import time
storage = 0
storage_limit = 100
def farm(storage, storage_limit):
  while storage < storage_limit:
    storage += 1
    time.sleep(1)
    print(storage)
farm(storage, storage_limit)
print(storage)

2 Answers2

1

Here is one example of code that does what you are asking about. It uses the global keyword and eliminates the storage argument in the farm() function.

import time

global storage
storage = 0
storage_limit = 100

def farm(storage_limit):
    global storage
    while storage < storage_limit:
        storage += 1
        #time.sleep(1)
        print(storage)
    return storage

farm(storage_limit)
print(storage)        

Here is another way. It changes farm() to return the modified value of its local variable storage, and it changes the call to farm() to update the different variable at outer scope named storage based on this return value.

import time
storage = 0
storage_limit = 100

def farm(storage, storage_limit):
    while storage < storage_limit:
        storage += 1
        #time.sleep(1)
        print(storage)
    return storage

storage = farm(storage, storage_limit)
print(storage)        
Yaakov Bressler
  • 9,056
  • 2
  • 45
  • 69
constantstranger
  • 9,176
  • 2
  • 5
  • 19
  • its not working, whenever i run the script all it does is print out the storage/storage limit two times. im looking to make it loop and print every number every time it is added +1 until it reaches 100. – Yakobu2 Mar 02 '22 at 16:16
  • @Yakobu2 sorry, looks like there was an indentation error on the `print()` statement in my code samples. I've edited my answer to fix this. Please try again. – constantstranger Mar 02 '22 at 16:33
  • @Yakobu2, were you able to get this to work? Is there anything more you need help with? – constantstranger Mar 02 '22 at 22:02
  • i used @obeskenobes code and it worked – Yakobu2 Mar 03 '22 at 12:53
0
import time
global storage
storage = 0
storage_limit = 100
def farm(storage_limit):
    global storage
    while storage < storage_limit:
        storage += 1
        time.sleep(1)
        print(storage)
    return storage
farm(storage_limit)
print(storage)

Is this what you're looking for? As previously mentioned, you need to reference the global variable within the function if that's what you want to adjust.

DanMack
  • 59
  • 6