Contents
- loop.py
- pick4winner.py
- sumtillenter.py
- while.py
- whilevsfor.py
loop.py 1/5
[top][prev][next]
# What does this loop do?
count = 1
while count > 0:
print count
count += 1
pick4winner.py 2/5
[top][prev][next]
# Simulate Pick 4 lottery game - selecting ping pong balls at random
# By CS111
import random
# define constants that are easy to change so that our
# program is flexible
NUM_BALLS = 4
MIN_VALUE = 0
MAX_VALUE = 9
# Create the format for the number
numFormat = ""
for num in xrange(NUM_BALLS-1):
numFormat += "#-"
numFormat += "#"
pickedNum = raw_input("What is your pick? (" + numFormat + ") ")
# Accumulator variable for the winning number
winningNum = ""
for num in xrange(NUM_BALLS-1):
# generate a random number (simulating the ping pong ball machine
# spitting out a random ping pong ball)
randomNum = random.randint(MIN_VALUE, MAX_VALUE)
# add the random number to the winning number
winningNum = winningNum + str(randomNum)
# add the hyphen to the winning number
winningNum += "-"
# add the final random number to the winning number
winningNum += str(random.randint(MIN_VALUE, MAX_VALUE))
# display the winning number
print "The winning number is", winningNum
if pickedNum == winningNum:
print "Congratulations! You're the big winner!!!!!!"
else:
print "Please waste more money and play again."
sumtillenter.py 3/5
[top][prev][next]
# Sum up numbers from the user
# By CS111
# Accumulator for the sum of the numbers
sum = 0
userInput = raw_input("Enter a number or hit enter to stop: ")
# Loop until user enters ""
while userInput != "":
# convert the raw_input to a number
userNum = float(userInput)
# add that number to the sum
sum = sum + userNum
print "The running total is", sum
# prompt again
userInput = raw_input("Enter a number or hit enter to stop: ")
# Display the final results
print "The sum of your numbers is", sum
while.py 4/5
[top][prev][next]
# Example of a while loop
# by Sara Sprenkle
print "While Loop Demo"
i = 0
while i < 10:
print "i equals", i
i += 1
print "Done", i
whilevsfor.py 5/5
[top][prev][next]
# Compares a while loop with a for loop
# by Sara Sprenkle
# WHILE LOOP
print "While Loop Demo"
i=0
while i < 10:
print "i equals", i
i += 1
print "Done", i
# FOR LOOP
print "\nFor Loop Demo"
for i in xrange(10):
print "i equals", i
print "Done", i
Generated by GNU enscript 1.6.4.