【问题标题】:Not defined name in cash register challenge收银机挑战中未定义名称
【发布时间】:2022-06-19 02:25:26
【问题描述】:

在几年没有用 python 编写之后,甚至在只参加过大学课程之前尝试了这个挑战。我正在尝试这个挑战并且遇到了一个未定义的变量,即使我将它声明为一个全局变量。我错过了什么?

import sys
# import numpy as np
# import pandas as pd
# from sklearn import ...

pp, ch = map(float, input().strip().split(";"))

#makes a dictionary of key value pairs of values as given in challenge
coins = {
    'PENNY': .01,
    'NICKEL': .05,
    'DIME': .10,
    'QUARTER': .25,
    'HALF DOLLAR': .50,
    'ONE': 1.00,
    'TWO': 2.00,
    'FIVE': 5.00,
    'TEN': 10.00,
    'TWENTY': 20.00,
    'FIFTY': 50.00,
    'ONE HUNDRED': 100.00
    
}

# first order check for values to continue
if ch < pp:
    print('ERROR')
    quit()
elif ch == pp:
    print('ZERO')
    quit()
#if values can be compared they start here
else:
    def change_back(x):
        global change_back, listy
        change_back = round(change_back - x, 2)
        listy= []#round to two decimals
        listy.append(x)
        
        change_back = round((ch-pp),2)
        named_list = list(dict.key(coins))
        entered_list = list(dict.values(coins))
        
#while loop to check for values entered in the dictionary, associates with a particular dictionary value
        while change_back not in entered_list:
            if change_back > 100 :
                monies_returned(100)
            elif change_back > 50 :
                monies_returned(50)
            elif change_back > 20 :
                monies_returned(20)
            elif change_back > 10 :
                monies_returned(10)
            elif change_back > 5 :
                monies_returned(5)
            elif change_back > 2 :
                monies_returned(2)
            elif change_back > 1 :
                monies_returned(1)
            elif change_back > .50 :
                monies_returned(.50)
            elif change_back > .25 :
                monies_returned(.25)
            elif change_back > .10 :
                monies_returned(.10)
            elif change_back > .05 :
                monies_returned(.05)
            elif change_back > .01 :
                monies_returned(.01)
        listy.append(change_back)
        
    link_names = [] #establish blank index to compare
for n in range(len(listy)):
    ref = named_list.index(listy[i])
    link_names.append(named_list[ref])
    print(*sorted(link_names), sep= ",")

Jupyter 中的错误: NameError: name 'listy' 没有定义

【问题讨论】:

  • 你认为listy是在哪里定义的?
  • 当你进入 for 循环而不点击 else 子句时,问问自己你有哪些全局变量。

标签: python python-3.x


【解决方案1】:

在函数定义之前实例化listy = [],而不是在其中,并将global listy保留在原处

【讨论】:

    猜你喜欢
    • 2022-11-10
    • 2016-08-13
    • 2012-05-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多