Search code examples
pythonwhile-loopnested-loops

python nested loop with break


well im learning python and im trying to make this kind of text game and im stuck on while loop...what im trying to do is have list of things that can be used, and compare user's raw_input to this list, if they chose right one within 5 attempts continue, otherwise die with message. here is my code:

def die(why):
    print why
    exit(0)

#this is the list user's input is compared to
tools = ["paper", "gas", "lighter", "glass", "fuel"]
#empty list that users input is appended to
yrs = []
choice = None
print "You need to make fire"

while choice not in tools:
    print "Enter what you would use:"
    choice = raw_input("> ")
    yrs.append(choice)
    while yrs < 5:
        print yrs
        die("you tried too many times")
    if choice in tools:
        print "Well done, %s was what you needeed" % choice
        break

but choice is not being added to list yrs, it works with just one while loop but then it gonna go forever or until one of items in tools list is entered as users input, however id like to limit it to 5 tries and then enter with : die("You tried too many times") but it gives me die-message straight after the first attempt... I was searching this forum, didnt find satisfying answer, please help me


Solution

  • Try

    if len(yrs) < 5: 
       print yrs
    else:
       die("you tried many times")
    

    instead of while. The condition

    yrs < 5
    

    is always returning false, since yrs is a list and you are comparing it to an integer. This means that the while yrs < 5 loop is never executed since the condition yrs < 5 was never true. Your program skips this loop and calls the die() function, which makes it exit immediately. That's why you should put die in a conditional statement, as is the case on the above snippet of code.

    Please note that if you instead wrote:

     while len(yrs) < 5:
         print yrs
    

    this would also be incorrect, since the condition len(yrs) < 5 would evaluate to True the first time it was checked, so you would end up in an infinite loop in which the user would not be able to provide any input, on the length of which the condition len(yrs) < 5 would depend.

    You would want to compare yrs's length to 5 in an if statement (as written above) to see if the user's attempts are more than 5. If they are not more than 5 the code flow should go on to the final check (if choice in tools...) before repetition of the outer while loop, in order to enable the user to make another attempt.