Infinite loops

Here is the simplest possible example of an infinite loop:

while True:
     print("Praxis!")

This code will print "Praxis!" forever. The process works as follows:

  • Check if True is still true
  • Execture the while-block, i.e., print("Praxis!")
  • Check if True is still true
  • Execture the while-block, i.e., print("Praxis!")
  • Check if True is still true
  • Execture the while-block, i.e., print("Praxis!")
  • Check if True is still true
  • Execture the while-block, i.e., print("Praxis!") .......

Since True is always true, this will go on forever

A more complicated infinite loop

Here is a trickier example of an infinite loop:

def is_prime(n):
    '''Return True iff n is prime
    Arguments:
    n -- a  non-negative integer
    '''
    if n <= 1:
        return False

    for i in range(2, n):  
        if n % i == 0:   
            return False 

    return True

 if __name__ == '__main__':
     i = 3
     while not(i%2==0 and is_prime(i)) and i < N:
         print("I tried", i, "it didn't work")
         i += 1

Here is what we are doing there: we set i = 3, and then we keep repeating the block

print("I tried", i, "it didn't work")
     i += 1

and checking whether i is both even and prime. Since no i larger than 2 is both even and prime, this process will go on forever.