![]() |
Confused by 'break' in the official documents - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Confused by 'break' in the official documents (/thread-25825.html) |
Confused by 'break' in the official documents - Chuck_Norwich - Apr-12-2020 Found these examples in the documentation.Was looking up For/Else loops. They both use a break statement. Was a bit confused why the break statement was there so ran them both without the break statements and the output is the same! So why have them? Example 1. for n in range(2, 10): for x in range(2, n): if n % x == 0: print(n, 'equals', x, '*', n/x) breakExample 2 - which is adding an else statement to the above (which I get) for n in range(2, 10): for x in range(2, n): if n % x == 0: print(n, 'equals', x, '*', n//x) break else: # loop fell through without finding a factor print(n, 'is a prime number') RE: Confused by 'break' in the official documents - buran - Apr-12-2020 (Apr-12-2020, 06:22 PM)Chuck_Norwich Wrote: so ran them both without the break statements and the output is the same!That is not true, the output is different. First snippet, with break: First snippet, without break: There are 2 extra lines.break serve to break out (i.e. terminate the execution) of the loop early. In the example - 6 is evenly divisible by 2, so there is no need to continue searching for other divisors, obviously it's not prime number.Now, in the second snippet you have also extra else clause. If the loop exection finishes normally (i.e. not from break) this will be executed. if not clear, look at this step by step execution
RE: Confused by 'break' in the official documents - Chuck_Norwich - Apr-12-2020 ok. Yes.Thanks. The visualise Python site is perfect! |