Showing posts with label for. Show all posts
Showing posts with label for. Show all posts

Tuesday, 28 July 2015

Functions

#!/usr/bin/env python

# Functions allow us to include code in our programs that will only run when
# explicitly called and can be reused.

# Simple function example.
def allStars(n):
        for i in range(0,n):
                print "*"

# Main Program
run = True              
while run:
        x = raw_input("How many stars should I print? ")
        if str.isdigit(x):
                allStars(int(x))
                x = raw_input("Do you want another go? Press Y or N")
                if str.upper(x) == "N":
                        run = False
        else:
                print "%s is not a number." % x

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'