【问题标题】:Simple while loop until break in Python简单的while循环直到在Python中中断
【发布时间】:2012-05-14 13:00:58
【问题描述】:

一个非常简单的while循环语句会继续下面的程序直到用户键入“退出”?

例如,

while response = (!'exit')
    continue file
else
    break
    print ('Thank you, good bye!')
#I know this is completely wrong, but it's a try!

到目前为止我的文件:

#!/usr/bin/python
friends = {'John' : {'phone' : '0401',
        'birthday' : '31 July',
        'address' : 'UK',
        'interests' : ['a', 'b', 'c']},
    'Harry' : {'phone' : '0402',
        'birthday' : '2 August',
        'address' : 'Hungary',
        'interests' : ['d', 'e', 'f']}}
response = raw_input("Please enter search criteria, or type 'exit' to exit the program: ").split()
try:
    print "%s's %s is %s" % (response[0], response[1], friends[response[0]][response[1]])
except KeyError:
    print "Sorry, I don't know about that. Please try again, or type 'exit' to leave the program: "

【问题讨论】:

  • 即我的主要问题是是否有特定的语句表示“继续运行文件”

标签: python while-loop break


【解决方案1】:

您的 while 循环将继续执行,直到您设置的条件为 false。所以你希望你的代码大部分都在这个循环中。完成后,您知道用户输入了“退出”,因此您可以打印错误消息。

#!/usr/bin/python
friends = {'John' : {'phone' : '0401',
        'birthday' : '31 July',
        'address' : 'UK',
        'interests' : ['a', 'b', 'c']},
    'Harry' : {'phone' : '0402',
        'birthday' : '2 August',
        'address' : 'Hungary',
        'interests' : ['d', 'e', 'f']}}

response = ['']
error_message = "Sorry, I don't know about that. Please try again, or type 'exit' to leave the program: "

while response[0] != 'exit':
    response = raw_input("Please enter search criteria, or type 'exit' to exit the program: ").split()
    try:
        print "%s's %s is %s" % (response[0], response[1], friends[response[0]][response[1]])
    except KeyError:
        print error_message
    except IndexError:
        print error_message

print ('Thank you, good bye!')

这段代码是你想要的开始,但它仍然有一些错误。看看你是否可以重组它,这样当用户输入“退出”时,错误消息就不会被打印出来。

【讨论】:

    【解决方案2】:

    continue 是一个不需要参数的关键字。它只是告诉当前循环立即继续到下一次迭代。它可以在whilefor 循环内使用。

    然后,您的代码应放在while 循环中,该循环将继续运行,直到满足条件。您的条件语法不正确。它应该是while response != 'exit':。因为您使用的是条件,所以不需要 continue 语句。只要值不是"exit",它将按设计继续。

    您的结构将如下所示:

    response = ''
    # this will loop until response is not "exit"
    while response != 'exit':
        response = raw_input("foo")
    

    如果您想使用continue,如果您要对响应进行其他各种操作,可能会使用它,并且可能需要提前停止并重试。 break 关键字是一种类似的循环作用方式,但它表示我们应该立即完全结束循环。您可能还有其他一些破坏交易的条件:

    while response != 'exit':
        response = raw_input("foo")
    
        # make various checks on the response value
        # obviously "exit" is less than 10 chars, but these
        # are just arbitrary examples
        if len(response) < 10:
            print "Must be greater than 10 characters!"
            continue  # this will try again 
    
        # otherwise
        # do more stuff here
        if response.isdigit():
            print "I hate numbers! Unacceptable! You are done."
            break
    

    【讨论】:

      【解决方案3】:
      #!/usr/bin/python
      friends = {
          'John' : {
              'phone' : '0401',
              'birthday' : '31 July',
              'address' : 'UK',
              'interests' : ['a', 'b', 'c']
          },
          'Harry' : {
              'phone' : '0402',
              'birthday' : '2 August',
              'address' : 'Hungary',
              'interests' : ['d', 'e', 'f']
          }
      }
      
      def main():
          while True:
              res = raw_input("Please enter search criteria, or type 'exit' to exit the program: ")
              if res=="exit":
                  break
              else:
                  name,val = res.split()
                  if name not in friends:
                      print("I don't know anyone called {}".format(name))
                  elif val not in friends[name]:
                      print("{} doesn't have a {}".format(name, val))
                  else:
                      print("{}'s {} is {}".format(name, val, friends[name][val]))
      
      if __name__=="__main__":
          main()
      

      【讨论】:

        猜你喜欢
        • 2020-09-29
        • 1970-01-01
        • 2017-07-31
        • 2014-02-14
        • 2014-03-22
        • 2014-03-09
        • 1970-01-01
        • 1970-01-01
        • 2023-02-03
        相关资源
        最近更新 更多