break 和continue 使用while 循环来处理列表和字典 while -else

函数input() 的工作原理,input() 接受一个参数:即要向用户显示的提示 或说明,让用户知道该如何做。在这个示例中,Python运行第1行代码时,用户将看到提示Tell me something, and I will repeat it back to you: 。程序等待用户输入,并在用户按回车键后继续运行。输入存储在变量message 中,接下来的print(message) 将输入呈现给用户:

message = raw_input("Tell me something, and I will repeat it back to you: ")
print(message)

Tell me something, and I will repeat it back to you: Hello everyone!
Hello everyone!

while 循环简介
for 循环用于针对集合中的每个元素都一个代码块,而while 循环不断地运行,直到指定的条件不满足为止。
prompt = “\nTell me something, and I will repeat it back to you:”
prompt += "\nEnter ‘quit’ to end the program. "
message = “”
while message != ‘quit’:
message = raw_input(prompt)
print message

Tell me something, and I will repeat it back to you:
Enter ‘quit’ to end the program. Hello everyone!
Hello everyone!
Tell me something, and I will repeat it back to you:
Enter ‘quit’ to end the program. Hello again.
Hello again.
Tell me something, and I will repeat it back to you:
Enter ‘quit’ to end the program. quit
quit
这个程序很好,唯一美中不足的是,它将单词’quit’ 也作为一条消息打印了出来.

使用break 退出循环
要立即退出while 循环,不再运行循环中余下的代码,也不管条件测试的结果如何,可使用break 语句。break 语句用于控制程序流程,可使用它来控制哪些代码行将执行,
哪些代码行不执行,从而让程序按你的要求执行你要执行的代码。
例如,来看一个让用户指出他到过哪些地方的程序。在这个程序中,我们可以在用户输入’quit’ 后使用break 语句立即退出while 循环:
prompt = “\nPlease enter the name of a city you have visited:”
prompt += "\n(Enter ‘quit’ when you are finished.) "
while True:
city = input(prompt)
if city == ‘quit’:
break
else:
print("I’d love to go to " + city.title() + “!”)
以while True 打头的循环将不断运行,直到遇到break 语句。这个程序中的循环不断输入用户到过的城市的名字,直到他输入’quit’ 为止。用户输入’quit’
后,将执行break 语句,导致Python退出循环:
Please enter the name of a city you have visited:
(Enter ‘quit’ when you are finished.) New York
I’d love to go to New York!
Please enter the name of a city you have visited:
(Enter ‘quit’ when you are finished.) San Francisco
I’d love to go to San Francisco!
Please enter the name of a city you have visited:
(Enter ‘quit’ when you are finished.) quit

list.pop 可以指定pop哪一项(默认最后一项)会返回pop的值
list.remove 仅删除

Python List sort()方法

list.sort(cmp=None, key=None, reverse=False)
参数

cmp -- 可选参数, 如果指定了该参数会使用该参数的方法进行排序。
key -- 主要是用来进行比较的元素,只有一个参数,具体的函数的参数就是取自于可迭代对象中,指定可迭代对象中的一个元素来进行排序。
reverse -- 排序规则,reverse = True 降序, reverse = False 升序(默认)。

在循环中使用continue
要返回到循环开头,并根据条件测试结果决定是否继续执行循环,可使用continue 语句,它不像break 语句那样不再执行余下的代码并退出整个循环。continue 语句,让Python忽略余下的代码,并返回到循环的开头

在这里插入图片描述
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值