Quick question about Python loops...

Discussion in 'Mac Programming' started by ZipOTrousers, Aug 15, 2008.

  1. ZipOTrousers macrumors newbie

    Joined:
    Jul 1, 2008
    #1
    I'm new to learning Python and haven't programmed much since I left school at the beginning of the summer. Im trying to write a program that will give a user 3 attempts to guess my name:

    Code:
    count = 0
    name = raw_input("Try and guess my name: ")
    
    if name != "Andrew":
        count + 1
    else:
        print "Well done, thats right!"
        
    while name != "Andrew" and count < 3:
        print "Sorry, try again!"
    As it is, if the user inputs an incorrect name instead of displaying the error message and re asking for the name, it just gets trapped and repeatedly displays the error message until the program is stopped. Now in something I'm familiar with like VB I'd know how to do this, but with python I don't know how to loop the whole asking for input process until count = 3. This is an exercise from the wikibook on Python btw. How do i structure the program to do this? Thanks.
     
  2. lee1210 macrumors 68040

    lee1210

    Joined:
    Jan 10, 2005
    Location:
    Dallas, TX
    #2
    Not a python pro, but I think it should be:
    Code:
    count = 0
    name = ""
    while name != "Rumpelstiltskin" and count < 3:
      name = raw_input("Try and guess my name: ")
    
      if name != "Rumpelstiltskin":
        count + 1
        print "Sorry, try again!"
      else:
        print "Well done, thats right!"
    
    -Lee
     
  3. HiRez macrumors 603

    HiRez

    Joined:
    Jan 6, 2004
    Location:
    Western US
    #3
    Don't you need to increment by

    Code:
    count = count + 1
    or

    Code:
    count += 1
    ? "count + 1" by itself makes no sense because there is no assignment happening there.
     
  4. lee1210 macrumors 68040

    lee1210

    Joined:
    Jan 10, 2005
    Location:
    Dallas, TX
    #4
    Balls, in my reorganization i didn't even notice that.
     
  5. WebMongol macrumors member

    Joined:
    Sep 19, 2004
    Location:
    Bay Area, CA
    #5
    Or you can use for loop:
    Code:
    for i in range(3):
        name = raw_input("Try and guess my name: ")
        if name == "Andrew":
            print "well done!"
            break
        else:
            print "try again"
    
    
     
  6. lee1210 macrumors 68040

    lee1210

    Joined:
    Jan 10, 2005
    Location:
    Dallas, TX
    #6
    This is more an issue of style, but I like loops to end when the loop condition is false. break is fine, but I guess I would rank:
    exit loop via false condition > break >>> goto

    At least there is a loop condition in your example. I really don't enjoy:
    Code:
    while(true/1/.true.)
    -Lee
     

Share This Page