基于字典的switch case中的NameError

时间:2015-05-22 19:33:11

标签: python dictionary switch-statement

我没有使用python的经验,所以我想我会开始考虑我的新兴趣。我遇到一个问题,当谈到一个开关案例,python没有,在谷歌搜索后我发现大多数使用字典样式方法,你可以在下面看到。它是一个小型的.py文件,我正在构建复制ATM风格的系统,只是为了让我熟悉所有python的选项。

while True:
    print ("Who are you?")
    name = input().lower()

    if re.match("^[A-Za-z]*$", name):
        break
    else:
        print('Please enter a valid name')


print('Hello ' + name)

print("Please enter your PIN " + name)
pin = input()


accounts = {"stephen" : stephen,
           "Dean" : Dean,
           "Jennifer" : Jennifer,
           "Liam" : Liam,
           "Billie" : Billie,
           "Decky" : Decky,
           "Joel" : Joel,
}

accounts[name]()

def stephen():
    if pin == 1234:
        print("Pin Accepted")
    else:
        print("Wrong PIN")

def Dean():
    if pin == 1344:
        print("Pin Accepted")
    else:
        print("Wrong PIN")

现在的问题是,当我到达输入引脚部分时,它会返回错误,说明以下内容:

  

options = {" stephen" :stephen,NameError:name' stephen'未定义

任何想法可能是什么?看看这个例子,我觉得我把一切都搞定了,但是我无法通过Google搜索特定的错误找到答案。

3 个答案:

答案 0 :(得分:4)

由于您尝试使用stephen而收到错误,因此尚未定义。在定义函数后创建字典。

答案 1 :(得分:3)

Python是interpreted language,这意味着代码是由解释器逐行执行的,而不需要先编译。因此,当您尝试将函数stephen输入字典时,函数stephen未定义,因为它仅在稍后的脚本中定义。在将函数输入字典之前定义函数writeData,您的脚本将起作用。

答案 2 :(得分:1)

public String[] fillArray(...)

1)accounts = {"stephen" : stephen, "Dean" : Dean, "Jennifer" : Jennifer, "Liam" : Liam, "Billie" : Billie, "Decky" : Decky, "Joel" : Joel, } 字典中的值会导致错误。无论是变量还是函数,都必须在使用前定义它们。

2)删除accounts词典

中的最后一个逗号

这里有一个简单的样本:

account