I’m at the very beginning with Python so my knowledge is quite noob level.
Anyway, I have found this example online:
JavaScript
x
10
10
1
for num in range(10,20): #to iterate between 10 to 20
2
for i in range(2,num): #to iterate on the factors of the number
3
if num%i == 0: #to determine the first factor
4
j=num/i #to calculate the second factor
5
print(f"{num} equals {i} * {j}")
6
break #to move to the next number, the #first FOR
7
else: # else part of the loop
8
print(f"{num} is a prime number")
9
break
10
Here the result from the example:
JavaScript
1
11
11
1
10 equals 2 * 5
2
11 is a prime number
3
12 equals 2 * 6
4
13 is a prime number
5
14 equals 2 * 7
6
15 equals 3 * 5
7
16 equals 2 * 8
8
17 is a prime number
9
18 equals 2 * 9
10
19 is a prime number
11
Unfortunately by running that code on Jupyter it returns:
JavaScript
1
11
11
1
10 equals 2 * 5
2
11 is a prime number
3
12 equals 2 * 6
4
13 is a prime number
5
14 equals 2 * 7
6
15 is a prime number ### THIS IS THE ERROR
7
16 equals 2 * 8
8
17 is a prime number
9
18 equals 2 * 9
10
19 is a prime number
11
I can’t really find the error here, any advice?
Advertisement
Answer
I guess your attempt was
JavaScript
1
10
10
1
for num in range(10, 20):
2
for i in range(2, num):
3
if num % i == 0:
4
j = num / i
5
print(f"{num} equals {i} * {j}")
6
break
7
else:
8
print(f"{num} is a prime number")
9
break
10
whereas the correct code must be like
JavaScript
1
9
1
for num in range(10, 20):
2
for i in range(2, num):
3
if num % i == 0:
4
j = num / i
5
print(f"{num} equals {i} * {j}")
6
break
7
else:
8
print(f"{num} is a prime number")
9
Note (i) different indentation level for else
clause, and (ii) no second break
. You might want to be more careful about indentation in python.
Here, else
belongs to for
, not if
(and this distinction is realized by the indentation). For this, this documentation might be helpful. In summary, for ... else
behaves like this: once the for
loop ends, else
part is executed, unless the loop was terminated by a break
.