简体   繁体   中英

Why does this code not go to an infinite loop? (Python)

I'm currently beginning to learn Python specifically the while and for loops.

I expected the below code to go into an infinite loop, but it does not. Can anyone explain?

N = int(input("Enter N: "))
number = 1
count = 0

while count < N:
    x = 0
    for i in range(1, number+1): 
        if number % i == 0: 
             x = x + 1 
    if x == 2:
        print(i)
        count = count + 1
    number = number + 1
  1. For this code to not infinitely loop, count needs to be >= N .

  2. For count to increase, x needs to be equal to 2 .

  3. For x to be equal to 2 the inner for loop needs to run twice:

      for i in range(1, number+1): if number % i == 0: x = x + 1 
  4. For the inner for loop to run twice number must not have factors besides 1 and the number itself. This leaves only prime numbers. The inner loop will always set x == 2 when number is a prime number. As there are an infinite amount of prime numbers, count >= N will eventually be satisfied.

Try to change N to number :

while count < N:
while count < number:

Ok let's dissect your code.


N = int(input("Enter N: "))
number = 1
count = 0

Here you are taking user input and setting N to some number, for the sake of brevity let's say 4. It gets casted as an int so it's now an integer. You also initialize a count to 0 for looping and a number variable holding value 1.


while count < N:
    x = 0
    for i in range(1, number+1): 
        if number % i == 0: 
             x = x + 1 
    if x == 2:
        print(i)
        count = count + 1
    number = number + 1

Here you say while count is less than N keep doing the chunk of code indented. So in our N input case (4) we loop through until count is equal to 4 which breaks the logic of the while loop. Your first iteration there's an x = 0 this means everytime you start again from the top x becomes 0. Next you enter a for loop going from 1 up to but not including your number (1) + 1 more to make 2. you then check if the number is divisible by whatever i equals in the for loop and whenever that happens you add 1 to x. After iteration happens you then check if x is 2, which is true and so you enter the if block after the for loop. Everytime you hit that second if block you update count by adding one to it. now keep in mind it'll keep updating so long as that if x == 2 is met and it will be met throughout each iteration so eventually your while loop will break because of that. Hence why it doesn't go forever.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM