Chapter 7 用户输入和while循环
函数input()让程序暂停运行,等待用户输入一些文本。获取用户输入后,Python将其存储在一个变量中。
name=input("please enter your name:")
print("hello, "+name+"!")
please enter your name:lu
hello, lu!
有时候,提示可能超过一行,例如,你可能需要指出获取特定输入的原因。在这种情况下,可将提示存储在一个变量中,再将该变量传递给函数input() 。这样,即便提示超过
一行,input() 语句也非常清晰。
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("\nHello, " + name + "!")
If you tell us who you are, we can personalize the messages you see.
What is your first name? Eric
Hello, Eric!
使用函数input()时,Python将用户输入解读为字符串。
使用函数int(),可以让Python将输入视为数值。函数int() 将数字的字符串表示转换为数值表示:
>>> age = input("How old are you? ")
How old are you? 21
>>> age = int(age)
>>> age >= 18
True
处理数值信息时,求模运算符(%)是一个很有用的工具,它将两个数相除并返回余数:>>>4%3 1 5%3 2 6%3 0
练习题7-1~7-3
car=input("What kind of car do you want to rent?")
print("Let me see if I can find you a " + car +"!")
people=input("How many people?")
if int(people)>8:
print("there is no available table.")
else:
print("there are available tables.")
number=input("please input a number:")
if int(number)%10 ==0 :
print("it can be divided by 10")
else:
print("It cannot be divided by 10.")
for 循环用于针对集合中的每个元素都一个代码块,而while 循环不断地运行,直到指定的条件不满足为止。
current_number=1
while current_number <= 5:
print(current_number)
current_number+=1
1
2
3
4
5
可使用while 循环让程序在用户愿意时不断地运行,如下所示。我们在其中定义了一个退出值,只要用户输入的不是这个值,程序就接着运行:
prompt="\nTell me something, and I will repeat it back to you:"
prompt+="\nEnter 'quit' to end the program."
message=""
while message !='quit':
message=input(prompt)
if message != 'quit':
print(message)
在要求很多条件都满足才继续运行的程序中,可定义一个变量,用于判断整个程序是否处于活动状态。这个变量成为标志。你可让程序在标志为True时继续运行,并在任何事件导致标志的值为False时让程序停止运行。这样,在while语句中就只需要检查一个条件-标志的当前值是否为True,并将所有测试(是否发生了应将标志设置为False)的事件都放在其他地方,从而让程序变得更为整洁。
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)
要立即退出while循环,不再运行循环中余下的代码,也不管条件测试的结果如何,可使用break语句。
prompt="\nPlease enter the name of a city you have visited:"
prompt+="\n(Enter 'quit' when you are finished.)"
while True:
city=input(prompt)
if city == 'quit':
break
else:
print("I'd love to go to " + city.title() +"!")
要返回到循环开头,并根据条件测试结果决定是否继续执行循环,可使用continue语句,它不像break语句那样不再执行余下的代码并退出整个循环。
current_number=0
while current_number <10:
current_number += 1
if current_number % 2 == 0:
continue
print(current_number)
1
3
5
7
9
练习题7-4~7-6
prompt="what kind of toppings do you want to add?"
while True:
topping=input(prompt)
if topping == 'quit':
print('finished')
break
else:
print("we will add " + topping +"to your pizza.")
prompt="How old are you?\n(input 'quit' to stop)"
while True:
age=input(prompt)
if age == 'quit':
print("\nthe program has been stopped.")
break
age=int(age)
if age < 3:
print('The fee has been waived.')
continue
if age >= 3 and age < 12:
print("you need to pay 10 dollars.")
continue
if age>12:
print("you need to pay 15 dollars.")
for循环是一种遍历列表的有效方式,但在for循环中不应修改列表,否则将导致Python难以跟踪其中的元素。要在遍历列表的同时对其进行修改,可使用while循环。通过将while循环同列表和字典结合起来使用,可实际、存储并组织大量输入,供以后查看和显示。
unconfirmed_users=['alice','brian','candace']
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:Candace
Verifying user:Brian
Verifying user:Alice
The following users have been confirmed:
Candace
Brian
Alice
第3章中使用函数remove()来删除列表中的特定值,这之所以可行,是因为要删除的值在列表中只出现了一次。如果要删除列表中所有包含特定值的元素,只需添加while循环即可。
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’]
可使用while循环提示用户输入任意数量的信息。
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(name+"would like to climb "+response+".")
练习题
sandwich_orders=['sandwich_a','sandwich_b','sandwich_c']#熟食店
finished_sandwiches=[]
for sandwich in sandwich_orders:
print("I made your tuna sandwich")
finished_sandwiches.append(sandwich)
print("These sandwiches has finished: " )
for sandwich in finished_sandwiches:
print(sandwich)
print('there is no pastrami on sold')
sandwich_orders=['sandwich_a','sandwich_b','sandwich_c', 'pastrami','pastrami']
while 'pastrami' in sandwich_orders:
sandwich_orders.remove('pastrami')
finished_sandwiches=[]
for sandwich in sandwich_orders:
print("I made your tuna sandwich")
finished_sandwiches.append(sandwich)
print("These sandwiches has finished: " )
for sandwich in finished_sandwiches:
print(sandwich)
prompt=‘if you could visit one place in the world, where would you go?’
places=[]
active=True
while active:
place=input(prompt)
places.append(place)
if place == ‘no place’:
active=False
for place in places:
print(place)