如何返回循环开始?

时间:2014-04-01 20:35:57

标签: python loops for-loop input

search_room = raw_input("Search the:")

if search_room == "classroom":
    print "You quitly make your way to the classroom, which is empty besides last night's homework"
    sleep(3)
    print "Enter 'inspect' into the command line to inspect the homework, or enter exit, to return to the kitchen."
    action = raw_input("Command:")

    if action == "inspect":
        print "Hmph, uncompleted. Thats strange."
        print "Enter 'inspect' into the command line to inspect the homework, or enter exit, to return to the kitchen."
        action = raw_input("Command:")
    if action == "exit":
        print "you return to the kitchen"
        search_room = raw_input("Search the:")
        if action == "classroom":

我试图弄清楚如何使用这个循环让我可以在厨房和教室之间来回穿梭,但如果我在退出后尝试回到教室,我会收到一条错误消息关于以后的循环'。

2 个答案:

答案 0 :(得分:0)

如果我正确理解你的问题,你试图找出如何设置一个循环,让你从厨房回到教室等等,而不需要嵌套无限的条件。我建议你有一个外部while(true)循环功能的步骤序列,并添加条件来检查移动是否有效(去厨房,你当前必须在教室,并已进入退出,等)< / p>

答案 1 :(得分:0)

你需要将代码块放在它自己的循环中,并带有一个简单的布尔值Sentinel值(while not stop),如果在任何时候将stop设置为true,则无限循环将停止。还要记住python缩进对于区分代码范围的重要性,与java之类的语言不同,只要在{}之间放置代码,无关紧要。除非你使用if..elif这是我认为你想要的,因为你正在比较同一范围内的同一个变量,所以每个if语句都会被单独执行。

此外,如果您有两个以上的房间,比如游戏线索中的某些内容,您应该为每个房间定义某种范围。如果你在一个房间,你可以从那里访问哪些房间?我只使用一个简单的字典scopes完成了这项工作,其中每个房间都与一个可以访问的房间列表相关联,并在获取search_room时进行验证。他们现在只能互相访问,但您可以为每个列表添加更多内容以增加其他会议室的范围(并添加更多if个分支)

stop = false;
scopes = {"kitchen": ["classroom"], "classroom": ["kitchen"]}
locCur = "kitchen" #starting room
locPrev = "kitchen"
while not stop:
    search_room = raw_input("Search the:")
    if scopes[locCur].index(search_room) > -1 : #validate the room choice
        if search_room == "classroom":
            locCur = "classroom" #update current scope
            print "You quietly make your way to the classroom, which is empty besides last night's homework"
            sleep(3)
            print "Enter 'inspect' into the command line to inspect the homework, or enter exit, to   return to the kitchen."
            action = raw_input("Command:")
            if action == "inspect":
                print "Hmph, uncompleted. Thats strange."
                print "Enter 'inspect' into the command line to inspect the homework, or enter exit, to return to the kitchen."
                action = raw_input("Command:")
                if action == "inspect":
                    #print/do something else
            elif action == "exit":
                locCur = locPrev #set scope back to what it was
                print "you return to the " + locPrev
                locPrev = "classroom" #store this location
                continue
        elif search_room == "kitchen":
            #do something for this room
            print "message"
            continue
        elif search_room == "some other room":
            #do something for this room
            continue
        elif search_room == "stop":
            stop = true