一、函数input的工作原理
1.基本原理
(1).函数input()接受一个参数:即要向用户显示的提示或说明,让用户知道该怎么做。
注:如果使用的是python2.7,应使用raw_input()函数来提示用户进行输入。
(2).使用函数int(),可将python输入(字符串)转换为数值。
二、while循环简介
1.使用while循环
current_number=1
while(current_number<=5):
print(current_number)
current_number+=1
结果为:
1
2
3
4
5
2.使用标志
prompt="\nTell me something,and I will repeat it back to you:"
prompt+="\nEnter 'quit' to end the program."
active=True
while active:
message=input(prompt)
if message=='quit':
active=False
else:
print(message)
3.使用break退出循环
4.在循环中使用continue
5.避免无限循环
6.使用while循环来处理列表和字典
1).for循环是一种遍历列表的有效方式,但在for循环中不应再修改列表。
2).删除包含特定值的所有列表元素
pets=['dog','cat','dog','goldfish','cat','rabbit','cat']
print(pets)
while 'cat' in pets:
pets.remove('cat')
print(pets)
结果为:
['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']
['dog', 'dog', 'goldfish', 'rabbit']
7.使用用户输入来填充字典
responses={}
#设置标志,指出调查是否继续
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 response?(yes/no)")
if repeat=='no':
polling_active=False
#调查结束,显示结果
print("\n--polling Results--")
for name,response in responses.items():
print(name+" would like to climb "+response +".")
结果为:
What is your name?"Eric"
Which mountain would you like to climb someday?"Denali"
Would you like to let another person response?(yes/no)"yes"
What is your name?"Lynn"
Which mountain would you like to climb someday?"Thumb"
Would you like to let another person response?(yes/no)"no"
--polling Results--
Lynn would like to climb Thumb.
Eric would like to climb Denali.