Reputation: 21
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
Upvotes: 1
Views: 69
Reputation: 2595
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')
Upvotes: 1
Reputation: 4125
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.
Upvotes: 1
Reputation: 110
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.
Upvotes: 0