-3

I've brought in these global variables from my main module into my other modules, but they won't update. I know this because I tried to print the value of the variables after they were supposed to have been updated.

All variables start at '0'

This is the 'module_doors'

def one(pills, batteries, lighter):
  while True:
    doorone = input("A, B or C?:\n").lower()
    if doorone.lower() not in ('a', 'b', 'c'):
      print("That item doesn't exist, try again.")
      print('')
    else:
      break
  if doorone.lower() == 'a':
    batteries = 1
    print('These could come in handy later.')

  if doorone.lower() == 'b':
    lighter = 1
    print("Maybe it's a light source. Doesn't look brand new though, not sure how long it'll last.")

  if doorone.lower() == 'c':
    pills = 1
    print('Could save your life, good choice.')

I've then tried to print them in another module to check, like this:

import module_doors

def lobby(pills, batteries, lighter):
  if lobbydeci.lower() == 'b':
    print("")
    time.sleep(0.3)
    print('Only one key remaining, Nice!')
    print('')
    print("It says '0001' on the tag.")
    module_spacing.spacing()
    module_doors.one(pills, batteries, lighter)
    module_doors.two(pills, batteries, lighter)
    print(batteries)
    print(lighter)
    print(pills)

This is printing just 0's for all the variable values, even though they were supposed to update.

Thanks

Lamb
  • 1
  • 1

3 Answers3

1

You should return those variables if they are modified in the functions and you want to keep the changes.

Then reassign them where you call the functions

something like this:

def one(pills, batteries, lighter):
    # some stuff
    return pills, batteries, lighter

def lobby(pills, batteries, lighter):
    # some stuff
    return pills, batteries, lighter

pills = 0
batteries = 0
lighter = 0

pills, batteries, lighter = one(pills, batteries, lighter)
pills, batteries, lighter = lobby(pills, batteries, lighter)

You could technically do this without passing parameters and using global variables, but really you shouldn't (see Pranav Hosangadi link in the comment to understand why)

PD: pills batteries and lighter seem to be items. If you expand your code to include more items you should consider refactoring the code and using lists or dictionaries (you don't want to end up passing 20 variables to your functions)

0

You should use return at end, because you not getting back the variables:

return batteries, lighter, pills

and in the second model:

pills, batteries, lighter = module_doors.one(pills, batteries, lighter)

  
Elicon
  • 206
  • 1
  • 11
0

Make sure that you return the values after you iterate them

return pills, lighter, batteries
natscage
  • 1
  • 1