简单的 while 循环直到在 Python 中中断 [英] Simple while loop until break in Python

查看:28
本文介绍了简单的 while 循环直到在 Python 中中断的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一个非常简单的 while 循环语句会继续下面的程序,直到用户输入exit"?

What would a very simple while loop statement be that would continue the below program until the user types "exit"?

例如

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

推荐答案

您的 while 循环将继续,直到您设置的条件为假.所以你希望你的代码主要在这个循环中.完成后,您知道用户输入了退出",因此您可以打印错误消息.

Your while loop will continue until the condition you've set is false. So you want your code to mostly be inside this loop. Once it's finished, you know the user entered 'exit' so you can print the error message.

#!/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!')

这段代码是你想要的开始,但它仍然有一些错误.看看您是否可以对其进行重构,以便在用户输入退出"时不打印错误消息.

This code is a start to what you want, but it still has some bugs. See if you can restructure it so the error message isn't printed when the user enters 'exit'.

这篇关于简单的 while 循环直到在 Python 中中断的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆