Python Forum

Full Version: Trying to understand
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi, I was trying to under stand this code (it's copied from somewhere else), I understood a lot but I am getting confused in this 1 thing, really sorry for this as I am very new to python.
1. If I remove i += 1 then the code just simply asks me to put a number and after that it does nothing goes on to the next line but if I add back i += 1 then everything runs fine.
Somebody tried to explain this to me but I am still confused.

Image- https://imgur.com/a/kCQpzZq
Post the code, not a link please.
This is terrible code for a prime number test. Terrible code usually means the code is meant to demonstrate something. I think this code is meant to demonstrate using a while loop with an else statement. A while loop runs until the loop condition is satisfied, or the loop is broken. If the loop condition is satisfied, the code in the else body is executed.
while loop_condition:
    loop body
else:
    else body
In your code:
loop condition
i <= num - 1
loop body
if num % i == 0:
    print(num, "is not a prime number")
    break
i += 1
else body
print(num, "is a prime number")
This is not a correct observation:
Quote: If I remove i += 1 then the code just simply asks me to put a number and after that it does nothing goes on to the next line
i += 1 is just a shorthand way of writing i = i + 1
If you remove the i += 1, the value of i doesn't change. It remains 2. If you entered an odd number greater than 1 the loop will run forever because the loop condition is always True
2 < num - 1
and the break condition is always False
num % 2 == 1 for odd numbers.
If you leave i += 1 in the loop, the value for i is incremented by 1 each time the loop runs. First time i == 2, then i == 3, 4, 5, 6, ..... until i > num - 1 or num % i == 0.
Output:
If you enter 3, the loop runs for i = 2; 2 <= 3 - 1 Loop condition is True 3 % 2 != 0 Break condition is False i += 1, so now i == 3. 3 <= 3 - 1, Loop condition is False. Exit loop and go to else block print(3, "is a prime number")
If you enter 4, you get a different result. i still starts at 2.
Output:
2 <= 3 - 1 Loop condition is True 4 % 2 == 0 Break condition is True. Execute the code in the body of the if statmement print(4, "is not a prime number")
Because the loop was ended by a break, the else block is not executed.