我能用forloop得到同样的结果吗?

2024-05-20 18:21:09 发布

您现在位置:Python中文网/ 问答频道 /正文

这段代码是完美的工作,但我想知道我是否可以得到相同的功能使用for循环?你知道吗

    storm_halted=False
    while True:
        input=raw_input(">  ")
        if "stay" in input:
            print dead("You were struck by lightning !")
        elif "wait" in input and not storm:
            print "The storm has stpped !"
            storm_halted=True
        elif "wait" in input and storm:
            print dead("You are lazy")
        elif "room" in input and storm :
            gold ()
        else:
            print dead("Type something")

Tags: and代码in功能youfalsetruefor
1条回答
网友
1楼 · 发布于 2024-05-20 18:21:09

对于这段代码,您不能将input用作变量,因此我将其重写为:

   choice = input("") #This will get a string that the user types.        

   if "stay" in choice: #This will execute the code below if the user has typed something with stay in it
        print dead("You were struck by lightning !")

    elif "wait" in choice and not(storm): #this will execute the code below if the user has typed something with the word wait in it and there is no storm(storm=False)
        print "The storm has stpped !"
        storm_halted=True

    elif "wait" in input and storm: #this will execute the code below if the user has typed something with the word wait in it and there is a storm (storm=True)
        print dead("You are lazy")
    elif "room" in input and storm : #this will execute the code below if the user has typed something with the word room in it and there is a storm (storm=True)
        gold ()
    else: #This code will execute if none of the above happen
        print dead("Type something")

至于暴风雨,英国人会说:暴风雨已经停止了。尽管如此,我认为你在elif中意外地颠倒了not(storm)和storm,这是偶然的——从等价物的意义来看。你知道吗

希望这能帮助你理解。要做到这一点,其实没有太多其他的方法,也绝对没有更简单的方法。你知道吗

相关问题 更多 >