aranthe ([personal profile] aranthe) wrote in [community profile] intro_to_cs 2010-01-15 10:04 pm (UTC)

Ex 1 with counted strikes

This was my first solution to Ex. 1. The exercise was kinda boring, so I embroidered it a little—not much, just printed a response for every try.


# login.py >> if exercise 1: Password guessing (login) program
# with reported strikes.

# Initialize a variables to hold password, counter and message prefix.
password = 'mellon'
strikes = 0
strike_msg = '\nSteee-rike '

# The user gets 3 tries.
while strikes < 3:

    # Request the user's password.
    strike = raw_input('Enter your password: ')

    # Check the input against the stored password.
    if strike == password:

        # If it matches, 
        print "\nThat's a homer!"     # print success
        strikes = 3                   # set counter to 3 to end while
    else:

        # If it doesn't match,
        strikes += 1                  # increment the counter

        # Add the current number of strikes to the message.
        output = strike_msg + str(strikes) + '!'

        # Print intermediate failure message.
        print output
        
        # Is this the last one?
        if strikes == 3: 

            # Print the final failure message.
            print "You're out!"

Post a comment in response:

This community only allows commenting by members. You may comment here if you're a member of intro_to_cs.
(will be screened if not on Access List)
(will be screened if not on Access List)
If you don't have an account you can create one now.
HTML doesn't work in the subject.
More info about formatting