0

The following python code prints "no" as it should

for _ in range(10):
    a = 5+i
    if a > 50:
       print ("yes")
print("no")

But so does the following

for _ in range(10):
    a = 5+i
    if a > 50:
       print ("yes")
else:
    print("no")

I've never seen an else without an if in other languages, yet here the else seems to line up with the for. How is this possible? Shouldn't Python regard the second version as a syntax error?

I entered something like the second version by accident in a larger script and the script seemed to work. I didn't understand why.

Mark Tolonen
  • 166,664
  • 26
  • 169
  • 251
  • Did you try looking up the syntax for Python's for-loop? It explains that in detail. See https://docs.python.org/3/reference/compound_stmts.html#for – paxdiablo Jul 18 '23 at 22:42
  • Python allows for/else loops but in my experience aren't used very often. In other words, you are confused because you are associating the else with an if but it is associated with the for loop. – mr_mooo_cow Jul 18 '23 at 22:56

0 Answers0