Cover page images (keyboard)

Loops

Don Miner & Sue Evans

Adapted from the CS1 Course at Swarthmore College by Lisa Meeden

Hit the space bar for next slide

Learning Outcomes

For Loops

range

Example: Factors

Iterating over sequences

>>> print range(1,5)
[1, 2, 3, 4]

Nested For Loops

Nested For Loop Exercise

You may not use Python's repetition operator, *, for this exercise.

While Loops

Interactive Loops

Sentinel Loops

Lots of Data

Post-test loop


# Filename:    getValidInt.py
# Author:      Sue Evans
# Date:        8/9/09
# Section:     All
# Email:       bogar@cs.umbc.edu
# Description: This program illustrates use of a while
#              loop to get values from the user within
#              a specified range, rejecting all bad input.
#              The function uses a post-test loop.

def getValidInt(question, min, max):

    # use a bad value to enter the loop
    value = max + 1

    # compose the prompt 
    prompt = question + " (" + str(min) + "-" + str(max) + "): "
    
    # continue to get values until the user enters a valid one
    while value == "" or value < min or value > max:
        value = raw_input(prompt)
        if len(value) != 0:
            value = int(value)

    # return a valid value
    return value

def main():


    print "\nThis program will give the classifications"
    print "of integers in the range you select.\n"

    START_QUES = "Enter the starting integer"
    END_QUES = "Enter the ending integer"
    
    start = getValidInt(START_QUES, 1, 10000)
    stop  = getValidInt(END_QUES, start, 10000)

    print "\nYou selected %d to %d.\n" % (start, stop)
    
main()

Let's watch it work.

linuxserver1.cs.umbc.edu[121] python getValidInt.py

This program will give the classifications
of integers in the range you select.

Enter the starting integer (1-10000): 10001
Enter the starting integer (1-10000): 0
Enter the starting integer (1-10000):
Enter the starting integer (1-10000): -2
Enter the starting integer (1-10000): 5
Enter the ending integer (5-10000): 4
Enter the ending integer (5-10000): 10001
Enter the ending integer (5-10000): 23

You selected 5 to 23.

linuxserver1.cs.umbc.edu[122]

Example: Menu

# Filename:    rectangles.py
# Author:      Sue Evans
# Date:        8/12/09
# Section:     all
# Email:       bogar@umbc.edu
#
# This program uses a menu to interact with the user.
# It also makes use of functions.



# findArea() finds the area of a rectangle
# Inputs: length and width
# Output: the area of the rectangle
def findArea(length, width):

    return length * width


# findPerimeter() finds the perimeter of a rectangle
# Inputs: length and width
# Output: the perimeter of the rectangle
def findPerimeter(length, width):

    return 2 * (length + width)


# drawRectangle() draws the rectangle using *s
# Inputs: length and width
# Output: none
def drawRectangle(length, width):

    print
    for i in range (0, length):
        for j in range (0, width):
            # if it's on the border print a star else a space
            if i == 0 or j == 0 or i == length - 1 or j == width - 1:
                print '*',
            else:
                print ' ',
        print


# enterDimensions() allows the user to enter
# the dimensions of a rectangle.
# Inputs: none
# Output: length and width
def enterDimensions():

    length = getValidInt("Enter the length", 1, 10)
    width = getValidInt("Enter the width", 1, 10)

    return length, width


# getValidInt() prompts the user to enter an
# integer in the specified range, rejects values
# not in that range by requiring new input, and
# only returns a valid integer.
# Inputs: the question of the prompt,
#         the minimum value in the range
#         and the maximum value in the range
# Output: an integer in the specified range
def getValidInt(question, min, max):

    # use a bad value to enter the loop
    value = max + 1

    # compose the prompt
    prompt = question + " (" + str(min) + "-" + str(max) + "): "

    # continue to get values until the user enters a valid one
    while value == "" or value < min or value > max:
        value = raw_input(prompt)
        if len(value) != 0:
            value = int(value)

    # return a valid value
    return value


# printMenu() prints the menu of choices
# Inputs: none
# Output: none
def printMenu():
    print "\n\tE - Enter a rectangle's dimensions\n"
    print "\tA - Find the area of the rectangle\n"
    print "\tP - Find the perimeter of the rectangle\n"
    print "\tD - Draw the rectangle\n"
    print "\tQ - Quit\n\n"


# printGreeting() prints the greeting to the user
# Inputs: none
# Output: none
def printGreeting():
    print "\nThis program works with rectangles."
    print "It can find the area and perimeter of a rectangle"
    print "whose dimensions you've entered and can even draw it."
    print "You can continue to enter as many rectangles as you want.\n"


def main():

    choice = ''

    printGreeting()
    length, width = enterDimensions()

    while choice != 'Q' and choice != 'q':
        printMenu()
        choice = raw_input("Enter your choice : ")

        if choice == 'E' or choice == 'e':
            length, width = enterDimensions()
        elif choice == 'A' or choice == 'a':
            area = findArea(length, width)
            print "The area of a %d x %d" % (length, width),
            print "rectangle is %d\n\n" % area
        elif choice == 'P' or choice == 'p':
            perimeter = findPerimeter(length, width)
            print "The perimeter of a %d x %d" % (length, width),
            print "rectangle is %d\n\n" % perimeter
        elif choice == 'D' or choice == 'd':
            drawRectangle(length, width)
        elif choice == 'Q' or choice == 'q':
            print
        else:
            print choice + ' is not a valid choice\n'


main()

Let's see it run.

linuxserver1.cs.umbc.edu[101] python rectangles.py

This program works with rectangles.
It can find the area and perimeter of a rectangle
whose dimensions you've entered and can even draw it.
You can continue to enter as many rectangles as you want.

Enter the length (1-10): 4
Enter the width (1-10): 7

        E - Enter a rectangle's dimensions

        A - Find the area of the rectangle

        P - Find the perimeter of the rectangle

        D - Draw the rectangle

        Q - Quit


Enter your choice : a
The area of a 4 x 7 rectangle is 28



        E - Enter a rectangle's dimensions

        A - Find the area of the rectangle

        P - Find the perimeter of the rectangle

        D - Draw the rectangle

        Q - Quit


Enter your choice : p
The perimeter of a 4 x 7 rectangle is 22



        E - Enter a rectangle's dimensions

        A - Find the area of the rectangle

        P - Find the perimeter of the rectangle

        D - Draw the rectangle

        Q - Quit


Enter your choice : D

* * * * * * *
*           *
*           *
* * * * * * *

        E - Enter a rectangle's dimensions

        A - Find the area of the rectangle

        P - Find the perimeter of the rectangle

        D - Draw the rectangle

        Q - Quit


Enter your choice : E
Enter the length (1-10): 9
Enter the width (1-10): 4

        E - Enter a rectangle's dimensions

        A - Find the area of the rectangle

        P - Find the perimeter of the rectangle

        D - Draw the rectangle

        Q - Quit


Enter your choice : d

* * * *
*     *
*     *
*     *
*     *
*     *
*     *
*     *
* * * *

        E - Enter a rectangle's dimensions

        A - Find the area of the rectangle

        P - Find the perimeter of the rectangle

        D - Draw the rectangle

        Q - Quit


Enter your choice : w
w is not a valid choice


        E - Enter a rectangle's dimensions

        A - Find the area of the rectangle

        P - Find the perimeter of the rectangle

        D - Draw the rectangle

        Q - Quit


Enter your choice : e
Enter the length (1-10): 12
Enter the length (1-10): 4
Enter the width (1-10): 10

        E - Enter a rectangle's dimensions

        A - Find the area of the rectangle

        P - Find the perimeter of the rectangle

        D - Draw the rectangle

        Q - Quit


Enter your choice : d

* * * * * * * * * *
*                 *
*                 *
* * * * * * * * * *

        E - Enter a rectangle's dimensions

        A - Find the area of the rectangle

        P - Find the perimeter of the rectangle

        D - Draw the rectangle

        Q - Quit


Enter your choice : q

linuxserver1.cs.umbc.edu[102] 

break

continue

Caution!

# Filename:    beers.py
# Author:      An unknown UMBC student
# Date:        Every semester
# Section:     Can never remember
# Email:       unknown@umbc.edu
# 
# How many beers are left after 5 rounds?

def main(): 

    beers = 1.0
    CHORUS = 'bottles of beer'

    # You'd think this loop will count down from 1.0 to 0.0 by
    # step -0.2, singing each verse as it goes, but does it ? 
    while beers != 0.0:
        print "%f %s on the wall" % (beers, CHORUS)
        print "%f %s" % (beers, CHORUS)
        print "Take a fifth down, pass it around"
        beers -= 0.2
        print "%e %s on the wall\n" % (beers, CHORUS)

 
main()

linuxserver1.cs.umbc.edu[101] python beers.py
1.000000 bottles of beer on the wall
1.000000 bottles of beer
Take a fifth down, pass it around
8.000000e-01 bottles of beer on the wall

0.800000 bottles of beer on the wall
0.800000 bottles of beer
Take a fifth down, pass it around
6.000000e-01 bottles of beer on the wall

0.600000 bottles of beer on the wall
0.600000 bottles of beer
Take a fifth down, pass it around
4.000000e-01 bottles of beer on the wall

0.400000 bottles of beer on the wall
0.400000 bottles of beer
Take a fifth down, pass it around
2.000000e-01 bottles of beer on the wall

0.200000 bottles of beer on the wall
0.200000 bottles of beer
Take a fifth down, pass it around
5.551115e-17 bottles of beer on the wall

0.000000 bottles of beer on the wall
0.000000 bottles of beer
Take a fifth down, pass it around
-2.000000e-01 bottles of beer on the wall

-0.200000 bottles of beer on the wall
-0.200000 bottles of beer
Take a fifth down, pass it around
-4.000000e-01 bottles of beer on the wall

-0.400000 bottles of beer on the wall
-0.400000 bottles of beer
Take a fifth down, pass it around
-6.000000e-01 bottles of beer on the wall

-0.600000 bottles of beer on the wall
-0.600000 bottles of beer
Take a fifth down, pass it around
-8.000000e-01 bottles of beer on the wall

I had to stop this code from running using ^c
It's an endless loop.

The Lesson