Advertisement
gruntfutuk

nested for loop example

Apr 20th, 2017
204
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.67 KB | None | 0 0
  1. #!/usr/bin/env python
  2. # nested for loops to find prime number
  3. # (not an efficient approach, just illustration of loops)
  4.  
  5. num = range(2, 200)  # change range to check as desired
  6.  
  7. for n in num:  # check each n in range to see if is prime
  8.     for x in range(2, n):  # divide each n(umber) by all lower numbers from 2 up
  9.         if n % x == 0:  # if modulo n/x is 0, no remainder, then not prime
  10.             print("{:4d} is NOT a prime number".format(n))
  11.             break  # no point looking at higher values of x
  12.  
  13.     else:  # nobreak - i.e. what to do if iter completed without match
  14.         print("{:4d} is     a prime number".format(n))  # didn't break, must be prime
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement