繁体   English   中英

Python函数返回不正确的数据

[英]Python function is returning incorrect data

下面的代码在单独的文件中引用时返回错误的数据。 当给定的数据与if / else语句不匹配时,它将再次循环遍历该函数,但是另一个文件(client_type)中的变量仍然是错误的选择。

功能:

def create_client():
    client_type = input()

    if client_type == 'Mickey':
        return 'Mickey'
    elif client_type == 'Jenny':
        return 'Jenny'
    elif client_type == 'McElroy':
        return 'McElroy'
    else:
        create_client()

调用该函数:

client_type = functions.create_client()

if client_type == 'Mickey':
    client = functions.client(3, 5, 2)
elif client_type == 'Jenny':
    client = functions.client(5, 2, 3)
elif client_type == 'McElroy':
    client = functions.client(4, 1, 5)
else:
    print('Error on choosing client in function create_client.')

您的问题是,当函数递归时,它什么也不返回。

你应该改变

else:
    create_client()

else:
    return create_client()

现在,这不是一个直接的答案,但是在这种情况下,您实际上不应该使用递归,最好使用循环:

def create_client():
    while True:
        client_type = input()

        if client_type == 'Mickey':
            return 'Mickey'
        elif client_type == 'Jenny':
            return 'Jenny'
        elif client_type == 'McElroy':
            return 'McElroy'

这样不会耗尽递归调用堆栈,并节省了资源。

我什至会继续使用dict而不是if / elif的序列:

client_types = {
    'Mickey':  (3, 5, 2),
    'Jenny':   (5, 2, 3),
    'McElroy': (4, 1, 5),
}

那么您可以让您的代码搜索字典并返回正确的数字:

while True:
    t = input()
    if t in client_types:
        break
client = functions.client(*client_types[t])

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM