1

I am new to python and just in the initial phase of the basics. Can someone please explain me how the for loop in the below code works? and I really don't get how number 9 is getting 3 as inner value.

Kindly tell me how the loops executes. TIA.

CODE:

for outer in range(2,10):
 for inner in range(2,outer):
 if not outer%inner:
 print(outer,'=',inner,'*',int(outer/inner))
 break 
 else:
 print(outer,'is prime')

Output:
2 is prime
3 is prime
4 = 2 * 2
5 is prime
6 = 2 * 3
7 is prime
8 = 2 * 4
9 = 3 * 3
asked Jan 3, 2020 at 18:47

3 Answers 3

1

The inner loop runs multiple times for each execution of outer loop.

For value of 9 of outer loop, the inner loop executes from 2 to outer value.

answered Jan 3, 2020 at 18:53
Sign up to request clarification or add additional context in comments.

Comments

1

I commented your code below, It should explain what is going on.

# This loop loops through numbers 2-9, and assigns them to the variable 'outer'
for outer in range(2,10):
 # This loop loops through numbers 2-(outer-1), and assigns them to the variable 'inner'
 for inner in range(2,outer):
 # if outer % inner == 0, the code is executed
 if not outer%inner:
 # When this is executed for 9, it will print 9 = 3 * 3
 print(outer,'=',inner,'*',int(outer/inner))
 break 
 else:
 print(outer,'is prime')
answered Jan 3, 2020 at 18:55

1 Comment

first comment loops through 2-9 and assigns them to variable would be correct
0

Your inner loop executes multiple times for every one execution of the outer loop.

For an outer value of 9 your inner loop will execute from 2 to (outer) which is 9.

answered Jan 3, 2020 at 18:51

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.