我有一个功能,要求用户提供一些输入并对输入进行一些检查。如果输入不符合几个条件,它将再次运行该功能,并再次要求用户输入一些信息。
但是,当我随后返回该函数时,它不仅返回最新输入,而且还返回错误输入。我究竟做错了什么?一些打印语句仅用于调试
def get_email(email):
print('starting email is',email)
while email == 'empty':
print('the email we use now is',email)
email = input()
print("your input email is",email)
if '@' not in email:
get_email('empty')
elif email[-1] == '@':
get_email('empty')
elif email[0] == '@':
get_email('empty')
print("the email we return is",email)
return email
get_email('empty')
答案 0 :(得分:1)
您通过两种方式滥用递归:首先,您没有使用递归调用的返回值:
def get_email(email):
print('starting email is',email)
while email == 'empty':
print('the email we use now is',email)
email = input()
print("your input email is",email)
if '@' not in email:
email = get_email('empty')
elif email[-1] == '@':
email = get_email('empty')
elif email[0] == '@':
email = get_email('empty')
print("the email we return is",email)
return email
print(get_email('empty'))
第二,如果一个简单的循环就足够了,那么就不应该在Python中使用递归。
def get_email(email):
print('starting email is', email)
# @ isn't in 'empty', so no need to check for empty specifically
while '@' not in email or email[-1] == '@' or email[0] == '@':
print('the email we use now is ', email)
email = input()
print('your input email is ', email)
print('the email we return is ', email)
return email