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

查看:207
本文介绍了简单的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循环将继续,直到您设置的条件为false。因此,您希望您的代码大部分位于此循环内。完成后,您知道用户输入了退出,因此可以打印错误消息。

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天全站免登陆