函数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忽略余下的代码,并返回到循环的开头
![](https://img.laitimes.com/img/__Qf2AjLwojIjJCLyojI0JCLiAzNfRHLGZkRGZkRfJ3bs92YsYTMfVmepNHL9kEVNdXTq1keRpXT1AnMMBjVtJWd0ckW65UbM5WOHJWa5kHT20ESjBjUIF2X0hXZ0xCMx81dvRWYoNHLrdEZwZ1Rh5WNXp1bwNjW1ZUba9VZwlHdssmch1mclRXY39CXldWYtlWPzNXZj9mcw1ycz9WL49zZuBnLwQTNxQzMyETM4ADNwkTMwIzLc52YucWbp5GZzNmLn9Gbi1yZtl2Lc9CX6MHc0RHaiojIsJye.png)