Skip to main content
 首页 » 编程设计

Python:调用外部函数时出现问题

2025年05月04日11落叶

我是 Python 的初学者,在使用函数时遇到了问题。我正在制作一个程序,其中我有很多参数供用户选择,我需要允许他们确认或拒绝他们的选择。这是代表我的问题的简化代码部分。

我的代码:

def confirm(function): 
    while True: 
        answer = raw_input('Are you sure? ') 
        if answer == 'yes': 
            break 
        elif answer == 'no': 
            return function() # if the user wants to change their name, recall function 
        else: 
            continue # to reprompt user if the answer is not "yes" or "no" 
 
def your_name(): 
    while True: 
        name = raw_input("What is your name? ") 
        if not name: 
            continue # to reprompt user if they do not enter anything 
        else: 
            confirm(your_name) 
            print 'Congratulations! You have a name!' 
            break 
your_name() 

运行此程序时,它会打印祝贺字符串的次数与 answer 收到输入的次数相同。
我的输出:

What is your name? Bastion 
Are you sure? no 
What is your name? Artex 
Are you sure? no 
What is your name? Falcor 
Are you sure? yes 
Congratulations! You have a name! 
Congratulations! You have a name! 
Congratulations! You have a name! 

My intention is for the congratulatory message to be printed just one time. How can I edit my function(s) in order to achieve this?

What I've tried:
I have attempted all of these, using the exact same input values I used in my output block above. Within the section of confirm(function) that says:

if answer == 'no': 
    return function() 

我尝试将其更改为:

if answer == 'no': 
    function() 

在输出中,这将请求 answer raw_input 3 次,并在每次输入后发布祝贺消息。如果我这样写代码:

if answer == 'no': 
    print function() 

它将打印祝贺响应 3 次并且每次在下面的单独一行上打印None。我正在寻找一种优雅、干净的格式,所以这行不通。

请您参考如下方法:

所以你的问题是你正在创建一种无意义的递归函数,你不需要传递要再次调用的函数,因为你已经在函数内部了。我建议如下:

def confirm(): 
    while True: 
        answer = raw_input('Are you sure? ') 
        if answer == 'yes': 
            return True 
        if answer == 'no': 
            return False 
        else: 
            continue # to reprompt user if the answer is not "yes" or "no" 
 
def your_name(): 
    while True: 
        name = raw_input("What is your name? ") 
        if not name: 
            continue # to reprompt user if they do not enter anything 
        elif confirm(): 
            print 'Congratulations! You have a name!' 
            break 
your_name()