您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

简单的while循环,直到在Python中中断

简单的while循环,直到在Python中中断

您的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!')

这段代码是您想要的代码的开始,但是仍然存在一些错误。查看您是否可以对其进行重组,以便在用户输入“退出”时不显示错误消息。

python 2022/1/1 18:49:45 有342人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶