如何在Python中循环一系列函数?

时间:2016-02-07 03:25:20

标签: python

我想让main()重复,直到它再也不能了,因为在function_one()上有一个“找不到文件”。当我执行代码时,它从function_one到function_three并在那里停止。如何循环main()以便它再次重复功能序列?

 def main():
        (f,r) = function_one()
        (x,z) = function_two(f,r)
        function_three(x,z)

3 个答案:

答案 0 :(得分:4)

使用class DatabasesViewAll(LoginRequiredMixin, View): raise_exception = True def get(self, request): print( request.session.get('user_id')) databases = Database.objects.all() serialized_databases = serializers.serialize('json', databases) return JsonResponse({'result':'success', 'data':serialized_databases}) def post(self, request): return JsonResponse({'result':'error', 'message':'Operação Inválida'}) 循环:

def std_login(request):
    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')
        user = authenticate(username=username, password=password)

        # Authentication Successfull
        if user is not None:
            request.session['user_id'] = user.id
            database = Database.objects.get(dweller__profile__user=user)

        # Authentication failed
        else:
            response_data = {}
            response_data['result'] = 'error'
            response_data['message'] = 'Usuário ou senha inválido.'
            return JsonResponse(response_data)

答案 1 :(得分:2)

正如已经建议的那样,使用try / except的while循环将运行良好,但要小心你捕获的内容。要尽可能具体。 this post中的更多信息。

如果您的功能并非都以例外结束, 您也可以通过手动引发异常来让它们返回成功或失败。

def main():
    c = float(1.00)
    # Uncomment the following line to see an unplanned exception / bug.
    # c = float(0.00)
    # That's is why it's important to only catch exceptions you are
    # expexting.
    # If you catch everything you won't see your own mistakes.

    while True:
        c += 2
        print('Main loop')
        try:
            (f, r) = function_one(c)
            (x, z) = function_two(f, r)
            function_three(x, z)
        except IOError:
            print('Controlled end, due to an IOError')
            break
        except ValueError as e:
            print('Intentionally stopped: %s' % e)
            break
    print("Program end")


# Will cause IOERROR if "thestar.txt" does not exist,
# Will continue on if you create the file.
def function_one(c):
    print('function_one')
    with open('thestar.txt', 'r') as bf:
        f = bf.read()
    # Doing work on the data ...
    r = 100 - c
    return (f, r)


# If the file does not contain the text "Cleese",
# this will hand-raise an exception to stop the loop.
def function_two(f, r):
    print('function_two')
    if 'cleese' in f.lower():
        x = 100 / r
        z = 'John ' + f
    else:
        raise ValueError('The parrot is just sleeping')
    return (x, z)


# you need to write "Cleese" to thestar.txt to get this far and keep
# the main loop going.
def function_three(x, z):
    print('function_three')
    # This is what decides when we are finished looping
    if x > 1:
        print('%s:%s' % (x, z))
    else:
        # Another diliberately raised exception to break the loop
        raise ValueError('The parrot is dead!')


if __name__ == '__main__':
    main()

使用变量而不是异常来做这件事是完全可以的,但这种方式更容易,而且它被认为是非常pythonic。

答案 2 :(得分:0)

使用def main(): while True: try: (f, r) = function_one() (x, z) = function_two(f, r) function_three(x, z) except WhateverErrors: break 循环。当任何函数抛出异常时,它将自动退出。