+ 3
Help me understand
contacts = [ ('James', '42'), ('Amy', '24'), ('John','31'), ('Amanda','63'), ('Bob', '18') ] a="hayk" for x in contacts: if a == x[0]: print("something") break else: print("Not found") SO THE QUESTION IS When i run this code there is no error BUT The right way to write is For… If… else… But here is this and it run as well,but i was expecting an error For… If… else… SO HOW DO I HAVE NO ERROR ABOUT indentation of else?
4 odpowiedzi
+ 7
Hayk Hakobyan ,
> when we use an *else clause* with the *if statement* and we are searching for 'Bob' the result is:
Bob
Not found
Not found
Not found
Not found
something
> when we use an *else clause* with the *for loop* and we are searching for 'Bob' the result is:
Bob
something
(so this is the correct way to build the logic. please read the link that lisa has posted)
+ 4
"The else keyword in a for loop specifies a block of code to be executed when the loop is finished"
https://www.w3schools.com/JUMP_LINK__&&__python__&&__JUMP_LINK/gloss_python_for_else.asp
+ 1
Thank You dear Lisa
+ 1
Thank You Lothar