Ex35 (and ex36, sort of) - is there an elegant way to convert the while-loop in bear_room() into a for-loop?


#1

Hi everyone and happy Christmas!

So I was wondering if it is possible to convert the following while-loop into a for-loop:

def bear_room():
    print("There is a bear here.")
    print("The bear has a bunch of honey.")
    print("The fat bear is in front of another door.")
    print("How are you going to move the bear?")
    bear_moved = False
    
    while True:
        choice = input(">")
        
        if choice == "take honey":
            dead("The bear looks at you then slaps your face off.")
        elif choice == "taunt bear" and not bear_moved:
            print("The bear has moved from the door.")
            print("You can go through it now")
            bear_moved = True
        elif choice == "taunt bear" and bear_moved:
            dead("The bear gets pissed off and chews your leg off.")
        elif choice == "open door" and bear_moved:
            gold_room()
        else:
            print("I got no idea what that means.")

I can think of a way to replace while with a couple of if-elif-elses but doing the exercise of using a for-loop is a riddle to me. I found a thread on reddit where someone suggested to use for+iter() to solve a similar problem. But I can’t really come up with an idea to use this in bear_room(). Do I need to create a list to iterate over which includes the choices from the if-elif-else-part of bear_room()?

I’m greatful for any help with this. Or does it just not make sense to use a for-loop in this case?


#2

Hey @berberpy I’m not a pro but I would say, it does not make sense to use a for loop in this case. A for-loop is great if you have a fixed set of repetitions. But you don’t have it here. The while loop can be broken in every if-statement and you can’t say in the beginning how many times the loop will be called.
What you can do instead is to replace the while-loop with a recursive function (a function that calls itself). For that you need to put everything inside the while loop in a function.


#3

Thanks for your reply. You’re probably right I guess. I was just wondering because I thought it’s a nice and tricky exercise to do a while–>for loop conversion for that case.


#4

Oh, I see, you want to drive yourself insane with an impossible task. Well, Zed is here to help:

https://wiki.python.org/moin/Generators

Basically you create a generator that you give to the for-loop, but the generator never ends. I’ll stop at that so you can try to figure it out, but I will warn you that this is a tough nut to crack and you might have to read a bunch of things on generators to figure it out. I always have to read about generators when I try to use them.


#5

Haha! I see what you mean with “insane” after reading the Python wiki article. I’ll get back to this after finishing the book. This seems to be beyond my abilities (for the moment).

BTW: This forum is most useful.