Tuesday 28 July 2015

Flow Control 1: for, for-else

#!/usr/bin/env python

# Simple for loop example.
for i in range(0,11):
        print "The value of i is %d." % i

# for-else example.
# This is taken directly from the Python documentation. The else statement
# looks as though it's in the wrong place. It's not. Python for loops can have
# else statements.
for n in range(2, 10):
        for x in range(2, n):
                if n % x == 0:
                        print n, 'equals', x, '*', n/x
                        break
        else:
                # loop fell through without finding a factor
                print n, 'is a prime number'

No comments:

Post a Comment