0
I wanted to do a Python program to find specific name in List:
Example using random names:
nomes = ['Melissa Renata Peixoto', 'Bruna Carla Henry Gomes', 'Carla Rosângela Brito', 'Carla Letícia Sebastiana Assis']
Using like this nomes.find("Carla")
Should appear in the output:
Carla Rosângela Brito
Carla Letícia Sebastiana Assis
Bruna Carla Henry Gomes
I tried to program like this:
while i != 4:
x = nomes[i].find("Carla")
if x == 0:
print(nomes[i])
else:
pass
i+=1
But there was no "Bruna Carla Henry Gomes" no output
it’s because you’re only taking cases where
Carla
is the first name (index=0). Useif!=-1
as a condition because thefind
returns -1 when substring is not found. Check this question:https://answall.com/questions/487894/qual-a-diferen%C3%a7a-among-the-m%C3%a9all-of-string-find-e-index-in-python– Lucas
Another detail is that
else: pass
is unnecessary and can be removed -pass
It’s basically the same as "does nothing" and usually serves to designate an empty block when language syntax requires you to have something. But how theelse
is not mandatory, and is not to do anything if you do not enter theif
, then remove thiselse: pass
from there. Finally, you can make it simpler: https://ideone.com/Re0U3U– hkotsubo