[Django]-Return can close Loop for? (python/django)

1👍

return terminates execution further and returns some desired value (default is None). Change indentation to make your code working :

def lerDoBanco(name):
    lista_names = [
        {'name': 'Joaquim', 'age': 20},
        {'name': 'João', 'age': 25},
        {'name': 'Ana', 'age': 27}
    ]

    for person in lista_names:
        if person['name'] == name:
            return person
    return {'name': 'Person not found', 'age': 0}

It will iterate all the values to find the person then if not found then the default value {'name': 'Person not found', 'age': 0} will be returned.

2👍

When you call return operator it will terminate the current function execution and return value. So if you will use return inside your loop, return will terminate the loop and the function and return some value.

0👍

From the moment you return you move out of the function, so out of the for loop as well.

What you thus can do is simply return the 'Person not found' at the end of the function:

def lerDoBanco(name):
    lista_names = [
        {'name': 'Joaquim', 'age': 20},
        {'name': 'João', 'age': 25},
        {'name': 'Ana', 'age': 27}
    ]

    for person in lista_names:
        if person['name'] == name:
            return person
    return {'name': 'Person not found', 'age': 0}

Note that if the data is stored in the database, it is better to make a queryset to filter at the database side. Databases are optimized to search effectively. You can also specify db_index=True on a column such that the database builds an index allowing much faster retrieval.

0👍

A loop ends when one of the following happens:

  1. loop condition evaluates to false
  2. break is used
  3. an exception is raised
  4. a return statement is executed

The points above are the same for every programming language

Leave a comment