gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 06:55:15 24 4
gpt4 key购买 nike

我是 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? BastionAre you sure? noWhat is your name? ArtexAre you sure? noWhat is your name? FalcorAre you sure? yesCongratulations! 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()

关于Python:调用外部函数时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28870085/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com