Jshee
Jshee

Reputation: 2686

variable defined in a function throws NameError: global name not defined when used in main

I'm trying to run my function: show_total() , but I get this error:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File ".\file.py", in <module>
    main()
  File ".\file.py", in main
    total_money = show_total(bags, coins, coin_to_bag)
NameError: global name 'coin_to_bag' is not defined

my code looks like:

def assign_coin_to_bag(bags, coins):
    coin_to_bag = {}
    print(bags)
    print('\n')
    print (coins)
    print('\n')
    for bag in bags:
        print('For bag: ' + bag )
        coin_type = input('\nWhich coin do you want to put in this bag? ')  #e.g. 0.25 * 2
        coin_amount = input('\nNumber of this type? ')  #e.g. 0.25 * 2
        mattress_status = 'stuffed'
        for coin in coins:
            coin_to_bag[bag] = [coin_type, coin_amount, mattress_status]
    print(coin_to_bag)
    return (coin_to_bag)

def main():
    bags = gather_bag()
    coins = gather_coin()
    coins_in_the_bag = assign_coin_to_bag(bags, coins)
    total_money = show_total(bags, coins, coin_to_bag)

main()

Thank you for your help!

Upvotes: 0

Views: 1580

Answers (1)

Kristj&#225;n
Kristj&#225;n

Reputation: 18813

coin_to_bag is a defined in the scope of assign_coin_to_bag, and is not accessible in main. You caught the return value of assign_coin_to_bag in coins_in_the_bag, and need to use that variable in your call to show_total.

There's a common error new programmers make, which is thinking the name of a variable needs to be the same wherever it's used, even across methods. In fact, the name of the variable means absolutely nothing to the computer. Good names are only there for humans.

As an exercise, we used to have students trace code like this:

def foo(one, three, two):
  print "%s %s %s" % (one, two, three)

def bar():
  return 1, 2, 4

three, two, one = bar()
foo(two, one, three)

Figure out what gets printed, and that will be good practice to break the variable naming habit.

Upvotes: 3

Related Questions