+ 2
Using else alongside for loop means that, the code in the else should run after normal execution of the for loop
29th May 2022, 4:01 PM
Faisal Issaka
Faisal Issaka - avatar
+ 2
I woud create a variable outside of the for loop with the default value "Not Found", inside the same as you use in print "{c[0]} is {c[1]}" and finally print the variable auside the for loop
29th May 2022, 5:33 PM
Cristian Baeza Jimenez
Cristian Baeza Jimenez - avatar
+ 1
But in the above case, there is break hence the else might not run since we are breaking out
29th May 2022, 4:05 PM
Faisal Issaka
Faisal Issaka - avatar
+ 1
Yarik Yaroo For-else loop is a thing in Python. There is a while-else, too. But yes, they are rarely used. Probably because we can do without them. But after reading about it, there are some merit in using them. https://book.pythontips.com/en/latest/for_-_else.html https://www.pythontutorial.net/python-basics/python-for-else/
30th May 2022, 1:43 AM
Bob_Li
Bob_Li - avatar
+ 1
Yarik Yaroo alternatively, you can create a dict from the list of paired tuples. c_dict = dict((k,v) for k,v in contacts) if name in c_dict: print(f"{name} is {c[name]}") else : print("Not found")
30th May 2022, 2:31 AM
Bob_Li
Bob_Li - avatar