Python Forum
Confused by 'break' in the official documents
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Confused by 'break' in the official documents
#2
(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:
Output:
4 equals 2 * 2.0 6 equals 2 * 3.0 8 equals 2 * 4.0 9 equals 3 * 3.0
First snippet, without break:
Output:
4 equals 2 * 2.0 6 equals 2 * 3.0 6 equals 3 * 2.0 8 equals 2 * 4.0 8 equals 4 * 2.0 9 equals 3 * 3.0
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.

Output:
2 is a prime number 3 is a prime number 4 equals 2 * 2 5 is a prime number 6 equals 2 * 3 7 is a prime number 8 equals 2 * 4 9 equals 3 * 3
if not clear, look at this step by step execution
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply


Messages In This Thread
RE: Confused by 'break' in the official documents - by buran - Apr-12-2020, 06:53 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  String int confused janeik 7 2,554 Aug-02-2023, 01:26 AM
Last Post: deanhystad
  Why Pip is not listed in the official Global Python Module index? quazirfan 2 1,402 Apr-21-2023, 10:55 AM
Last Post: snippsat
  Word documents merging crewdk 1 1,564 Apr-03-2023, 06:32 AM
Last Post: buran
  I am confused with the key and value thing james1019 3 1,862 Feb-22-2023, 10:43 PM
Last Post: deanhystad
  Pandas confused DPaul 6 3,777 Sep-19-2021, 06:45 AM
Last Post: DPaul
  is and '==' i'm confused hshivaraj 6 3,694 Sep-15-2021, 09:45 AM
Last Post: snippsat
  Сombine (Merge) word documents using python-docx Lancellot 1 14,289 May-12-2021, 11:07 AM
Last Post: toothedsword
  Confused with 'flags' tester_V 10 6,774 Apr-12-2021, 03:03 AM
Last Post: tester_V
  Copy documents to Teams using python SallySmith 0 3,090 Mar-23-2021, 04:27 AM
Last Post: SallySmith
Question Mouseover(Hover/Float) text in PDF documents ak52 1 3,353 Feb-24-2021, 06:13 PM
Last Post: nilamo

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020