help on ultra newbie program please
Gerhard Häring
gh at ghaering.de
Wed May 21 13:03:33 EDT 2003
cybernut wrote:
> [Tried to solve a problem in a Python tutorial]
Here's a solution using only "if" and "while" statements. I hope it's
somewhat enlightening.
#v+
# The correct password. 'Constants' are usually named all-capital.
CORRECT_PASSWORD = "unicorn"
# Number of times the user tried entering a password. Zero at the start.
tries = 0
# Wether the password is entered correctly. Default to a logically false
value.
password_ok = 0
# Execute the loop at most three times, and only as long as the correct
# password hasn't been entered.
while tries < 3 and not password_ok:
password = raw_input("Password:")
if password == CORRECT_PASSWORD:
password_ok = 1
tries += 1
if password_ok:
print "Welcome!"
else:
print "Go away!"
#v-
Don't worry if you can't solve some problems, yet. Learning to program
is learning about patterns (think of building blocks). I'd call this one
the "count and break at certain value" building block. You'll encounter
it very often.
These combiniations of control structures are kind of basic patterns.
Soon you'll have learnt all control structures and from then on the
major issue will be how to best organize your data :-)
This is where OOP (object oriented programming) will eventually enter
the game.
-- Gerhard
More information about the Python-list
mailing list