第七章 用户输入和while循环
1.函数input()
input()
函数input()让程序暂停运行,等待用户输入一些文本。
message = input("tell me what do you want to do :")
print(message)
prompt = "If you tell us who you are, we can personalize the messages you see."
prompt += "\nWhat is your first name? "
name = input(prompt)
print(f"\nHello, {name}!")
使用int()来获取数值输入
>>> age = input("how old are you?")
how old are you?21
>>> age>= 18
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: '>=' not supported between instances of 'str' and 'int'
此处发生错误是因为将用户输入字符串’21’与数值18比较,因此需要将用户输入的字符串转换数字
int():将输入视为数值,将数的字符串表示转换为数值表示
>>> age = int(age)
>>> age>=18
True
求模运算符
2.while循环简介
让用户选择何时退出
通过设定退出值
使用标志
在要求很多条件都满足才继续运行的程序中,可定义一个变量,用于判断整个程序是否处于活动状态,这个变量称为标志
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)
使用break退出循环
break语句用于控制程序流程,可用来控制哪些代码行将执行、哪些代码行不执行,在任何python循环中都可以使用break语句
在循环中使用continue
要返回循环开头,并根据条件测试结果决定是否继续执行循环,可使用continue语句,忽略余下代码,并返回循环开头
3.使用while循环处理列表和字典
前提:不应在for循环中修改列表,否则将导致python难以跟踪其中的元素,要在遍历列表的同时对其进行修改,可使用while循环,通过将while循环同列表和字典结合起来使用,可收集、存储并组织大量的输入,供以后查看和显示
在列表之间移动元素
unconfirmed_users = ['alice','brian','candace']
confirmed_users = []
while unconfirmed_users:
current_user = unconfirmed_users.pop()
print(f"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())
删除为特定值的所有列表元素
while循环配合remove()
pets = ['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']
print(pets)
while 'cat' in pets:
pets.remove('cat')
print(pets)
使用用户输入来填充字典
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 respond?(yes/no)")
if repeat == 'no':
polling_active = False
print("\n---poll results---")
for name,response in responses.items():
print(f"{name} would like to climb {response}.")
|