Problems with indents in Intermediate Python (Tuples) Code Coach | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Problems with indents in Intermediate Python (Tuples) Code Coach

Why does this work, contacts = [ ('James', 42), ('Amy', 24), ('John', 31), ('Amanda', 63), ('Bob', 18) ] name = input() for i in contacts: if name in i: print(str(i[0]) + " is " + str(i[1])) break else: print ("Not Found") where the indent before else is non-existent but not this? contacts = [ ('James', 42), ('Amy', 24), ('John', 31), ('Amanda', 63), ('Bob', 18) ] name = input() for i in contacts: if name in i: print(str(i[0]) + " is " + str(i[1])) break else: print ("Not Found") Where the indent is the typical below if one?

18th Mar 2023, 7:11 PM
Abdullah Ayman
4 Answers
+ 4
Don't really understand your question, but I guess you are asking why the code works both times, when the "else" statement is indented or not? Else can be used not only as "if-else" but also as "for..-else". Basically, in the first code, the "else" statement gets called only if the "for" statement runs through without any error/break. Since you should match the name with the contacts, the code doesn't necessarily get called. In the second code, you indent the "else" block to match with the "if" statement. That means that it gets called always when the statement isn't marked as True. So when trying to match the name with "i in contacts", you might get plenty of "Not Found" as outputs and at the end the other line. (In fact, if you entered "Bob" as the name, you would receive 4 lines of "Not Found" before the thing you want gets called.
18th Mar 2023, 7:27 PM
Paleon
Paleon - avatar
+ 2
I offer two meant-to-read codes that hopefully explain all the details about indentation and how you can use whitespace in general in Python. https://code.sololearn.com/cT5BRIbkia21/?ref=app https://code.sololearn.com/c9a0cG9dpVUr/?ref=app
19th Mar 2023, 1:23 PM
HonFu
HonFu - avatar
+ 1
Thanks, I didn't know about the for-else part.
18th Mar 2023, 7:40 PM
Abdullah Ayman
+ 1
Thanks, I understand now
19th Mar 2023, 3:38 PM
Abdullah Ayman