用户输入
1、用户输入:实现程序的可交互性——能够对用户输入作出响应。
input()函数:从标准输入读入一行文本,中间可以加提示语句,默认的标准输入是键盘。
可将提示存储在一个变量中,再将该变量传递给函数input()。这样,即便提示超过一行,input()语句也非常清晰。
prompt = "If you tell us who you are, we can personalize the messages you see."
prompt += "\nWhat is your first name?\n"
name = input(prompt)
print("Hello, " + name + "!")
输出:
If you tell us who you are, we can personalize the messages you see.
What is your first name?
YWCC #用户输入的信息
Hello, YWCC!
注意:用户输入的内容的是以字符串的形式表示!当用于比较等处理时,必须转换数据类型。
循环
1、for循环
for循环是针对集合中的每个元素的一个代码块
主要用来遍历任何序列的元素,如一个字符串、列表、字典等。
2、while循环
while循环不断地运行,直到指定的条件不满足为止。
prompt = "Are You DB? \n"
prompt += "Enter 'yes' to end the program :\n"
active = True
while active:
message = input(prompt)
if message == 'yes':
active = False
print('Yes,you are!')
else:
print(message + '?'+'You are DB!')
输出:
Are You DB?
Enter 'yes' to end the program :
no #用户输入
no?You are DB!
Are You DB?
Enter 'yes' to end the program :
yes #用户输入
Yes,you are!#退出循环
Process finished with exit code 0
这里的标志(active)用于判断整个程序是否处于活动状态,充当了程序的交通信号灯。适当地运用标志会而让程序变得更为整洁。
while … else 语句:在条件语句为 false 时执行 else 的语句块
num = 0
while num < 3:
print(num, " 小于3")
num +=1 #python中没有"++"运算符
else:
print(num, "大于等于3")
输出:
0 小于3
1 小于3
2 小于3
3 大于等于3
pass 语句:pass是空语句,是为了保持程序结构的完整性。pass 不做任何事情,一般用做占位语句。
3、break 和 continue语句
与其他语言相同:break 跳出循环体,continue跳过当前循环,继续执行下一轮循环。
4、无限循环
条件表达式永远不为 false 就会进入无限循环
x = 1
while x <= 5:
print(x)
# x += 1 如果没有这个语句,x永远等于1,就永远小于等于5,程序就会进入无限循环(死循环)
要避免进入无限循环,务必对每个while循环条件进行测试,确保它按预期那样结束。当然,无限循环在服务器上应对客户端的实时请求非常有用。
5、使用 while 循环来处理列表和字典
for循环是一种遍历列表的有效方式,但在for循环中不应修改列表,否则将导致Python难以跟踪其中的元素。要在遍历列表的同时对其进行修改,可使用while循环。通过将while循环同列表和字典结合起来使用,可收集、存储并组织大量输入,供以后查看和显示。
5.1 在列表之间移动元素
类似于for循环遍历列表,这里将一个列表中的元素,移动到另一个列表中:
unconfirmed_users = ['LiHua', 'XiaoMing', 'CanCan']
confirmed_users = []
while unconfirmed_users:
current_user = unconfirmed_users.pop()
print("Verifying user: " + current_user.title())
confirmed_users.append(current_user)
print("\nThe following users have been confirmed:")
for confirmed_user in confirmed_users:
print(confirmed_user.title())
输出:
Verifying user: Cancan
Verifying user: Xiaoming
Verifying user: Lihua
The following users have been confirmed:
Cancan
Xiaoming
Lihua
5.2 删除包含特定值的所有列表元素
之前使用remove()方法来删除列表中某个值的第一个匹配项,如果要删除列表中所有包含特定值的元素,可以使用while循环。
users = ['LiHua', 'XianHong', 'XiaoMing', 'CanCan','XianHong']
print (users)
while 'XianHong' in users:
users.remove('XianHong')
print (users)
输出:
['LiHua', 'XianHong', 'XiaoMing', 'CanCan', 'XianHong']
['LiHua', 'XiaoMing', 'CanCan']
5.3 使用用户输入填充字典
使用while循环可提示用户输入任意数量的信息。
information = {} #空字典
proceed = True
while proceed:
name = input("name: ")
year = input("year: " )
information[name] = year #直接就可创建键值对
repate = input("Would you continue?(yes/no): ")
if repate == "no":
proceed = False
print(information)
输出:
name: YW
year: 20
Would you continue?(yes/no): yes
name: LI
year: 24
Would you continue?(yes/no): yes
name: CC
year: 19
Would you continue?(yes/no): no
{'YW': '20', 'LI': '24', 'CC': '19'} #字典