7.用户输入和while循环
7.1函数input()的工作原理
函数input()接受一个参数:即要向用户显示的提示或说明,让用户知道该怎么做。
input()函数使用时,python将用户输入解读为字符串,如果需要输入数值,需要使用int()涵数。
处理信息时,他将两个数相除并返回余数:
4%3
1
求模运算符不会指出一个数是另一个数的多少倍,而只返回余数是多少。所以可以用xxx%2判断是否是even or odd
注意:python2.7中raw_input()和python3中的input()是一样的。
7.2 while循环简介
for循环用于针对集合中的每个元素的一个代码块,而while循环不断的运行,直到指定的条件不满足;
使用while循环:
break退出循环
continue:要返回到程序开头,并根据条件测试jieg结果决定是否继续执行循环。
避免无线循环
7.3使用while循环来处理lieb列表和字典
for循环是一种遍历列表的有效方法,dans但是在for循环中不应该修改列表,否则导致python难以跟踪其中的元素。
要在遍历列表的同时duiq对其进行修改,可使用while训话。通过将while循环tong同列表和字典结合起来使用,可收集,存储并组织大量输入,供以后查看并显示。
7.3.1 在列表之间移动元素
使用pop()将一个列表中的元素,搬移到另外一个列表中;
7.3.2删除包含特定值的所有lieb列表元素
remove()函数用来删除列表中的特定值,可以结合while循环,
pets=['dog','cat','dog','goldfish','cat','rabit','cat']
print(pets)
while 'cat' in pets:
pets.remove('cat')
print('pets')
以上实现remove()和while循环使用;删除cat;
7.3.3使用用户输入来填充字典
resposes={}
polling_active=True
while polling_active:
name=input("\nWhat is your name?")
response=input("Which mountain would you like to climb someday?")
responses[name]=response
repeat=input("Would you like to let another person respond?(yes/no)")
if repeat=='no':
polling_active=False
print("\n---poll result----")
for name,response in responses.item():
print(name+"would like to climb "+response+".")