-5

所以这是我的问题。我正在 python 3.3.2 中创建电话目录,我需要知道如何调用单独的函数。这是我的代码:

details = {"Toby": "123", "James": "234", "Paul": "345"}

print("Welcome To The Telephone Directory.\n")

print("To search out specific details, please type Search.\n To add a new person to the Directory, type Add.\n To change someone's details, please type Edit.")

search = input();

if(input() == search.strip() in "search Search SEARCH".split()):

    def search():

        print("Please enter the name of the customer.")
        customer = input()
        print("Number:" ,details.get(customer))
        if(customer not in details):
             print("I'm sorry, but the person you defined is not in the directory.")


flag = True
while flag:
    search()
    flag = input("Would you like to look up another person? [Y/N]") == "y"

if(input() == add.strip() in "add Add ADD".split()):
    def add():

        print("Please enter the name of the new entry.")
        name = input()
        print("Now enter the entry's phone number.")
        telNumber = input()
        details[name] = telNumber
        print("You have succesfully added a new entry:\n",name,"\n",telNumber)

所以我需要知道如何从一开始就调用 Add 函数。

有任何想法吗?

4

1 回答 1

1

您在 If 语句中定义从未真正被调用的函数

你想要这样的东西:

def do_definition(x): #defining your function, before you call it
    print(x)

y = 'foo'
if statement:
    do_definition(y) # this is actually calling the function

通常当你开始时你想先在顶部定义你的函数,然后在其他地方调用它们

我也认为你可能想检查你的语法。

当您正在制作时search = input()(顺便说一句,您不需要在它后面加上分号),然后您稍后在search()技术上调用这意味着您正在调用input()(),这很奇怪。

另外,如果您将def search():内容移出if语句,则您正在使用search代码中调用的另一个变量,这将导致生活混乱。

于 2013-09-20T18:17:00.177 回答