Python Forum
adding to code but still getting same output
Thread Rating:
  • 1 Vote(s) - 4 Average
  • 1
  • 2
  • 3
  • 4
  • 5
adding to code but still getting same output
#6
for i in range(1,4):
    for j in range(1,4):
        print( 'Running i =', i, 'j =', j )
    if i==2 and j==1 :
        print( 'Breaks inner loop at i=2 j=1' )
    break
In this code snippet if is still outside the second loop and also break is out of the if block, so the break statement is executed always when the execution reaches that line.
So when you start the code and enter the first loop i=1, then you enter the second loop and execute it entirely (i.e. j takes values 1, 2 3) and print the "Running..." string. Then you reach the if statement. When you reach it i=1 and j=3. so the first condition i==2 is evaluated to False AND the second condition j==1 is evaluated to False and thus the whole if statement is evaluated to False (because you have AND i.e. both conditions must be True to evaluate the entire statement as True). Thus "Breaks..." is not printed. Finally you reach the break statement and exit the loop in which it is (i.e. that is the outer loop, the one with i).
Reply


Messages In This Thread
RE: adding to code but still getting same output - by buran - Jul-11-2017, 09:18 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  No desired output for code. James349 1 1,092 May-19-2023, 05:43 PM
Last Post: deanhystad
  I need help for adding def to my code muzaffarshamsiev 1 1,743 Mar-28-2021, 02:18 AM
Last Post: BashBedlam
  Wrong output on my code. JTNA 2 8,008 Apr-04-2019, 01:55 PM
Last Post: JTNA
  Code to use output from arduino as input (help) Updownrightleft 0 2,279 Nov-03-2018, 11:04 PM
Last Post: Updownrightleft
  What this code will output and why? Valgard 4 4,012 Aug-30-2017, 01:41 PM
Last Post: Valgard

Forum Jump:

User Panel Messages

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