In the code, if the else statement outside for loop or inside? A detailed explanation would be very helpful. Thanks. | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

In the code, if the else statement outside for loop or inside? A detailed explanation would be very helpful. Thanks.

https://www.programiz.com/JUMP_LINK__&&__python__&&__JUMP_LINK-programming/examples/prime-number

7th Jun 2018, 10:56 AM
Deepayan Das
Deepayan Das - avatar
3 Answers
+ 6
The else is part of the for statement. It will only execute after the loop completes by falling out. Coded as if: i = 2 loop: if condition goto done i += 1 if i < num goto loop #else code done: #next statement
7th Jun 2018, 1:29 PM
John Wells
John Wells - avatar
+ 5
for i in range(2, num): #code1 else: #code2 If the for loop completes without hitting a break statement within 'code1', the else 'code2' will execute. Therefore, in your example, if the number isn't a prime, a break happens and the else code is ignored. If the number is prime, no numbers in the range will cause a break so the else executes stating the fact you have a prime.
7th Jun 2018, 1:18 PM
John Wells
John Wells - avatar
0
Is the else statement inside the else statement in line 16 inside the previous for loop? If that isn't the case then why is the if statement inside the for loop and else outside? The code seems to work but I can't quite understand it
7th Jun 2018, 1:22 PM
Deepayan Das
Deepayan Das - avatar