Help me understand | Sololearn: Learn to code for FREE!
Новый курс! Каждый программист должен знать генеративный ИИ!
Попробуйте бесплатный урок
+ 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?

2nd Mar 2023, 11:18 AM
Hayk Hakobyan
Hayk Hakobyan - avatar
4 ответов
+ 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)
2nd Mar 2023, 11:42 AM
Lothar
Lothar - avatar
+ 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
2nd Mar 2023, 11:27 AM
Lisa
Lisa - avatar
+ 1
Thank You dear Lisa
2nd Mar 2023, 11:44 AM
Hayk Hakobyan
Hayk Hakobyan - avatar
+ 1
Thank You Lothar
3rd Mar 2023, 7:20 AM
Hayk Hakobyan
Hayk Hakobyan - avatar