Session 5 - Computer Science

Download Report

Transcript Session 5 - Computer Science

Computer Science of
Graphics and Games
MONT 105S, Spring 2009
Session 5
While Loops
1
Repeating an action
Sometimes you would like to perform the same task several
times.
Enter Password:
xxx
Invalid Password.
Enter Password:
xyz
Invalid Password.
Enter Password:
abc
...
2
Diagram of a Loop
entry = raw_input("Enter password")
entry
not equal to
password?
False
True
entry = raw_input("Enter password")
Rest of Program
3
Writing a Loop in Python
# program passwordCheck.py
password = "sesame"
entry = raw_input("Please enter the password: ")
while entry != password:
print "Invalid password."
entry = raw_input("Please enter the password: ")
print "Password is correct. Welcome!"
# We will examine the execution of this code in class
4
General Form of a While Loop
while condition:
Python code
Condition
False
True
Python Code
Rest of Program
5
A loop with a counter
# program countingLoop.py
counter = 4
while counter > 0:
print "Countdown #", counter
counter = counter -1
# What is the output of this program?
6
Comparing values
Relational Operators allow you to compare two
values:
6 Relational Operators
B
A<B
A <= B
A>B
A >= B
True if A Less than B
True if A Less than or equal to B
True if A Greater than B
True if A Greater than or equal to
A == B
A != B
True if A Equal to B
True if A Not equal to B
7
Examples
x=4
y=6
EXPRESSION
VALUE
x<y
1 (true)
x+2<y
0 (false)
x != y
1 (true)
x + 3 >= y
1 (true)
y == x
0 (false)
y == x+2
1 (true)
8
Logical Expressions
Use logical operators, and, or and not, to combine logical
expressions.
p and q
true if both p and q are true
p or q
true if p or q or both are true
not p
true if p is false
9
Examples
age = 20
height = 70
Expression:
age < 25 and height < 75
Value
true
age > 20 or height < 75
true
age > 25 or height > 75
false
not age < 10
true
10
Password revisited
# Limit the number of guesses for passwords
password = "sesame"
entry = raw_input("Please enter your password: ")
count = 1
while entry != password and count < 3:
entry = raw_input( "Invalid. Try again: ")
count = count + 1
if entry != password:
print "Sorry. Only 3 guesses allowed."
else:
print "Welcome!"
11