用户输入和while循环
介绍
本章你将学习如何接受用户输入,和根据用户输入信息,让程序不断运行知道满足条件为止。
涉及函数:input();while()
函数input()的工作原理
函数input()让程序暂停运行,等待用户输入一些文本。获取用户输入后,python将其存储在
一个变量中,方便你使用。
message=input("tell me something ,and i will repeat it back to you:")
print("message")
编写清晰的程序
每当你使用函数input()时,都应当指定清晰而明白的提示,准确地指出你希望用户提供什么样的信息。
name=input("please enter your name:")
print(name)
有时候提示语句可能超过一行,这种情况下,可以将提示存储在一个变量中,再将变量传递给input().这样可以使input()语句非常清晰。
prompt="if you tell us who are, we cna personalize the messages you see."
prompt+="\nwhat is your first name?"
name=input(prompt)
print("hello"+name)
使用int()来获取数值输入
使用函数input()时,python将用户输入解释为字符串。
height = input("how tall aer you,in inches?")
height=int(height)
if height>=36:
print("\nyou're tall enough to ride!")
else:
print("\nyou'll be able to ride when you're alittle older.")
求模运算符%
number=input("enter a number,and i'll tell you if it's even or add:")
number=int(number)
if number % 2==0:
print("\nthe number "+str(number)+" is even.")
else:
print("\nthe number "+str(number)+" is odd.")
while循环简介
for 循环用于针对集合中的每个元素的一个代码块,而while循环不断地运行,直到指定条件不满足为止。
current_number=1
while current_mumber <= 5:
print(current_number)
current_number+=1
让用户选择何时退出
prompt="\ntell me something,and i will repeat it back to you:"
prompt+="\n enter 'quite' to end the program:"
message=""
while message != 'quit':
message = input(prompt)
print(message)
使用标志
在要求很多条件满足才能继续运行的程序中,可定义一个变量,用于判断整个程序是否处于活动状态。这个变量称为标志。你可以让程序在标志为true时才能继续运行,并在任何时间导致标志的值为falsh时让程序停止运行。这样在while语句中只需要检查当前标志是否为true,从而让程序变得更加简洁。
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退出循环
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':
break
else:
print(message)
在循环中使用continue
返回到循环的开头,并根据条件测试结果决定是否继续执行循环,可使用continue语句。
打印从1-10中奇数的循环:
current_number=0
while current_number < 10:
current_number+=1
if current_number % 2 ==0:
continue
else:
print(current_number)
提示:使用while时要避免无限循环
使用列表循环来处理列表和字典
for循环是一种遍历列表的有效方式,但是在for循环中不应该修改列表,否则导致python难以跟踪其中的元素。故要在遍历时对其进行修改,可以使用while循环。
通过while循环同列表和字典结合起来使用,可收集,存储并组织大量输入,供以后查看使用。
在列表之间移动元素
首先创建一个未验证的用户列表,再创建一个空列表,用于存储已经验证的用户。
unconfirmed_users=['alice','brian','candace']
confirmed_users=[]
while unconfirmed_users:
current_user=unconfirmed_users.pop()
print("verifying users:"+current_user.title())
confirmed_users.append(current_user)
for confirmed_user in confirmed_users:
print(confirmed_user)
while循环删除包含特定值的所有列表元素
使用函数remove()来删除列表中的特定值,只能删除重复一次的值;如果要删除列表中所有包含特定值的元素,可以使用while循环
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("\nwhich mountain would you like to climb someday:")
responses[name]=response
repeat=input("\nwould you like to let another persion respond?(yes/no)")
if repeat=='no':
polling_active=False
print("result is :")
for name,response in responses.items():
print(name+"would lie to climb"+response+'.')