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.
- [Django]-Uwsgi segmentation fault for one specific route
- [Django]-Django: login_redirect_url not working
- [Django]-Do I need to optimize database access in django templates?
- [Django]-Django Many-To-One relationship filter set
- [Django]-Checking the existence of a permission object in Django unit test
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.
- [Django]-How to delete ForeignKey field from model safely?
- [Django]-Importing a module which have the same name with a system module
- [Django]-In django-tastypie, can choices be displayed in schema?
0👍
A loop ends when one of the following happens:
- loop condition evaluates to false
- break is used
- an exception is raised
- a return statement is executed
The points above are the same for every programming language
- [Django]-Call a function with a button in django admin
- [Django]-Cannot assign "<class 'django.contrib.auth.models.User'>": "Model.user" must be a "User" instance
- [Django]-How to provide a source directory in the [tool.django-stubs] directive of a pyproject.tom file?
- [Django]-Django + nginx in docker containers: can not upload any file with forms
- [Django]-Is there a way to prevent the initial state from loading when my angularjs app starts up?