Ben wrote:
This is an exercise from the Non-programmers tutorial for Python
by Josh Cogliati.

The exercise is:

Write a program that has a user guess your name, but they only get 3
chances to do so until the program quits.

Here is my script:

--------------------------

count = 0
name = raw_input("Guess my name. ")

while name != 'Ben' and count < 3:

Everything inside this loop will only occur if the name doesn't equal 'Ben' and the count is less than 3.


count = count + 1

You increase the count by one, which allows your code to catch the case where count = 2 and now equals 3.


    if name != 'Ben' and count < 3:
        name = raw_input('Guess again. ')
    elif name == 'Ben' and count < 3:
        print "You're right!"
    else:
        print 'No more tries.'

Which is why you get this print message, because count is now equal to 3.


----------------------------------

Everything works except the line: print "You're right!"

But at no point does the program get an opportunity to print "No more tries.' because there is no point inside this loop where name == 'Ben'.


Could someone tell me what is wrong and give me a better alternative to
what I came up with.


Thank you

Ben

Also, you're duplicating a lot of your case testing. You check to see if the name is 'Ben' at the start, and then inside the loop, and the same for the counts.


I tried to write out a logical method of approaching this problem, but in truth this particular use-case isn't that simple is it?

Here's my contribution anycase:

count = 0
# Get first input
name = raw_input("Guess my name: ")
# Give the sucker two extra goes
while count < 2:
        # Check the value of name
        if name == 'Ben':
                print "You're right!"
                break
        else:
                name = raw_input("Try again: ")
# Of course, we haven't checked the sucker's last guess
# so we have to do that now.
if count == 2:
        if name == 'Ben':
                print "You're right!"
        else:
                print "No more tries for you!!!"


Hope this helps. Joal



--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to