Contents
- break.py
- eval_cond.py
- loop.py
- therapist.py
- while.py
- whilevsfor.py
break.py 1/6
[top][prev][next]
# Compares two versions of the same program, one uses break, one doesn't.
# Sara Sprenkle
# ---------- while LOOP ----------
# condition says when loop will continue
x=eval(input("Enter number: "))
while x % 2 != 0 :
print("Error!")
x = eval(input("Try again: "))
print(x, "is an even number. ")
# ---------- while LOOP USING break ----------
print("--"*10)
print("Again, but using break")
# have to look inside loop to know when it stops
while True :
x = eval(input("Enter number: "))
if x % 2 == 0 :
break
print("Error!")
print(x, "is an even number.")
eval_cond.py 2/6
[top][prev][next]
# Examples of advanced conditionals
# by Sara Sprenkle
x = 2
y = 3
z = 4
b = x==2
c = not b
# Note: because of precedence, we don't _need_ parentheses
# I added parentheses for readability/emphasis
d = (y<4) and (z<3)
print("d =", d)
d = (y<4) or (z<3)
print("d =", d)
d = not d
print(b, c, d)
loop.py 3/6
[top][prev][next]
# What does this loop do?
# Sara Sprenkle
count = 1
while count > 0:
print(count)
count += 1
therapist.py 4/6
[top][prev][next]
# The Very Simple Therapist
# CSCI 111
print("-"*60)
print("Welcome to computerized therapy!")
print("You will get your money's worth.")
print("Our session is over when you have nothing more to tell me.")
print("-"*60)
user_input = input("Tell me what's wrong.\n")
while user_input != "":
user_input = input("How does that make you feel?\n")
print("Thank you! Come again!")
while.py 5/6
[top][prev][next]
# Demonstrates a simple while loop.
# Trace through program and show what would be output.
# Sara Sprenkle
i = 0
while i < 10 :
print("i equals", i)
i+=1
print("Done", i)
whilevsfor.py 6/6
[top][prev][next]
# Code to compare 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 range(10):
print("i equals", i)
print("Done", i)
# To give exactly the same output as the while loop, would need to print out i+1
Generated by GNU Enscript 1.6.6.