【问题标题】:Can I use for-loop to get the same results? [closed]我可以使用 for-loop 来获得相同的结果吗? [关闭]
【发布时间】:2019-04-19 15:42:24
【问题描述】:

这段代码运行良好,但我想知道是否可以使用 for-loop 获得相同的功能?

    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")

【问题讨论】:

  • 请详细说明您的需求。您要解决的具体问题是什么。如果这是作业,请先展示你的一些尝试。
  • storm 未定义,您的函数永远不会被调用。请提供符合How to create a Minimal, Complete, and Verifiable example 的代码和明确表述的“我得到的是这个”“我想要的是那个”(如果适用:“这个是我的错误消息和堆栈跟踪” 我的代码产生)

标签: python while-loop boolean


【解决方案1】:

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

   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")

as for thestorm_halted = True 对应的英文是:暴风雨已经停止。尽管我认为您不小心将 elif 中的 not(storm) 和storm 颠倒过来了——从等价物的意义上来看。

希望这可以帮助您理解。真的没有太多其他方法可以实现这一点,而且绝对没有更简单的方法。

【讨论】:

  • @hhaeflinger 谢谢你,真的很感谢你的回答
猜你喜欢
  • 2015-08-05
  • 2023-03-12
  • 1970-01-01
  • 2015-02-23
  • 2021-06-22
  • 1970-01-01
  • 1970-01-01
  • 2013-12-18
  • 2021-07-17
相关资源
最近更新 更多