【问题标题】:Nested 'While' loop as a function嵌套的“While”循环作为函数
【发布时间】:2016-09-04 18:34:57
【问题描述】:
def Commands():
            command = raw_input("Type 'Mod', 'Run', 'Exit', or 'Help':")
            elif command == "Run" :
                restart = True
                break
if groups == 4 :
    restart = True
    while restart :
        restart = False
        Commands()

我怎样才能让这个功能正常工作? "restart = True" "break" 行不会再次启动前一个 "while" 循环。我在多个“if”语句中使用命令,并希望避免为每个语句重复 80 多行代码。我已经删除了正常工作的无关代码。

【问题讨论】:

  • 如果没有if,您就不能拥有elif。从您的 commands() 函数返回 TrueFalse 并使用它来确定您是否应该重新启动。
  • 我有 if elif 和 else,我删除了它们,因为它们工作正常,并希望保持代码简短,并专注于重启和中断不启动外部“while”循环的问题

标签: python-2.7


【解决方案1】:

而不是尝试在循环外使用use a global variablebreak(您当前的使用应该给出语法错误) - 您应该只return 一个布尔值并评估函数的返回值,例如:

def Commands():
    command = raw_input("Type 'Mod', 'Run', 'Exit', or 'Help':")
    if command.lower() == "run" :
        return True
        # changed this to use lower (so it sees run or Run or RUn)
        # and now it just returns a True value to say - keep going
    return False 
    # assuming that everything else means break out of loop just return False if not "Run"

while True:
    if not Commands():
        break

print "We're out"

您也可以将while循环设置为while Commands():并删除break,如this answer to a related question所示

【讨论】:

    【解决方案2】:

    当函数返回时,变量 restart 不正确,因为它超出了范围。一个简单的解决方案可能是让 Commands() 返回一个值 true 或 false,并在分配该值的 while 循环中重新启动。

    restart = Command() #Where command returns true or false
    

    Short Description of the Scoping Rules?

    【讨论】:

      【解决方案3】:

      使用返回值是最简单的。如果你想进一步消除样板,你可以使用异常:

      def Commands():
          command = raw_input("Type 'Mod', 'Run', 'Exit', or 'Help':")
          if command != "Run" :
              raise StopIteration
      if groups == 4 :
          try:
              while True:
                  Commands()
          except StopIteration:
              print('Done')
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-04-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多