Python 用户输入和while循环

Python Day 6 2020-4-12
Python 用户输入和while循环

函数 input()的工作原理
函数input()让程序暂停运行,等待用户输入一些文本。
函数input()接受一个参数:即要向用户显示的提示或说明,让用户知道该如何做。
程序等待用户输入,并在用户按回车键后继续运行。
1.编写清晰的程序
(1)使用函数input()时,都应指定清晰而易于明白的提示,准确地指出你希望用户提供什么样的信息——指出用户该输入任何信息的提示。
(2)在提示末尾包含一个空格,可将提示与用户输入分开,让用户清楚地知道其输入始于何处。
(3)提示可能超过一行,在这种情况下,可将提示存储在一个变量中,再将该变量传递给函数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)

2.使用 int()来获取数值输入
使用函数input()时,Python将用户输入解读为字符串。
将输入作为数字使用,可使用函数int(),它让Python将输入视为数值。函数int()将数字的字符串表示转换为数值表示。

>>> age = input("How old are you? ") 
How old are you? 21 
>>> age = int(age) 
>>> age >= 18 
True

3.求模运算符
处理数值信息时,求模运算符(%)是一个很有用的工具,它将两个数相除并返回余数。

while 循环简介
for循环用于针对集合中的每个元素都一个代码块,而while循环不断地运行,直到指定的条件不满足为止。
1.使用 while 循环

current_number = 1 
while current_number <= 5: 
 print(current_number) 
 current_number += 1

2.让用户选择何时退出
可使用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) 
 print(message)

3.使用标志
在要求很多条件都满足才继续运行的程序中,可定义一个变量,用于判断整个程序是否处于活动状态。这个变量被称为标志,充当了程序的交通信号灯。

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)

4.使用 break 退出循环
要立即退出while循环,不再运行循环中余下的代码,也不管条件测试的结果如何,可使用break语句。
在任何Python循环中都可使用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() + "!")

5.在循环中使用 continue
要返回到循环开头,并根据条件测试结果决定是否继续执行循环,可使用continue语句,它不像break语句那样不再执行余下的代码并退出整个循环。
6.避免无限循环
每个while循环都必须有停止运行的途径,这样才不会没完没了地执行下去。

使用 while 循环来处理列表和字典
1.在列表之间移动元素

# 首先,创建一个待验证用户列表
# 和一个用于存储已验证用户的空列表
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())

2.删除包含特定值的所有列表元素
我们使用函数remove()来删除列表中的特定值。

pets = ['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat'] 
print(pets) 
while 'cat' in pets: 
 pets.remove('cat') 
 
print(pets)

3.使用用户输入来填充字典
可使用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 + ".")

课后习题
7-1 汽车租赁:编写一个程序,询问用户要租赁什么样的汽车,并打印一条消息,如“Let me see if I can find you a Subaru”。

7-2 餐馆订位:编写一个程序,询问用户有多少人用餐。如果超过 8 人,就打印一条消息,指出没有空桌;否则指出有空桌。

7-3 10 的整数倍:让用户输入一个数字,并指出这个数字是否是 10 的整数倍。

7-4 比萨配料:编写一个循环,提示用户输入一系列的比萨配料,并在用户输入’quit’时结束循环。每当用户输入一种配料后,都打印一条消息,说我们会在比萨中添加这种配料。

7-5 电影票:有家电影院根据观众的年龄收取不同的票价:不到 3 岁的观众免费;3~12 岁的观众为 10 美元;超过 12 岁的观众为 15 美元。请编写一个循环,在其中询问用户的年龄,并指出其票价。

7-6 三个出口:以另一种方式完成练习 7-4 或练习 7-5,在程序中采取如下所有做法。
(1)在 while 循环中使用条件测试来结束循环。
(2)使用变量 active 来控制循环结束的时机。
(3)使用 break 语句在用户输入’quit’时退出循环。

7-7 无限循环:编写一个没完没了的循环,并运行它(要结束该循环,可按 Ctrl +C,也可关闭显示输出的窗口)。

7-8 熟食店:创建一个名为 sandwich_orders 的列表,在其中包含各种三明治的名字;再创建一个名为 finished_sandwiches 的空列表。遍历列表 sandwich_orders,对于其中的每种三明治,都打印一条消息,如 I made your tuna sandwich,并将其移到列表finished_sandwiches。所有三明治都制作好后,打印一条消息,将这些三明治列出来。

7-9 五香烟熏牛肉(pastrami)卖完了:使用为完成练习 7-8 而创建的列表sandwich_orders,并确保’pastrami’在其中至少出现了三次。在程序开头附近添加这样的代码:打印一条消息,指出熟食店的五香烟熏牛肉卖完了;再使用一个 while 循环将列表 sandwich_orders 中的’pastrami’都删除。确认最终的列表 finished_sandwiches 中不包含’pastrami’。

7-10 梦想的度假胜地:编写一个程序,调查用户梦想的度假胜地。使用类似于“If you could visit one place in the world, where would you go?”的提示,并编写一个打印调查结果的代码块。

#7-1
message=input('What kind of car would you like to rent?')
print('Let me see if I can find you a '+message+'.')
#7-2
meal=input('\nHow many people are there in your party?')
meal=int(meal)
if meal>8:
	print("I'm terribly sorry, but there are no seats available.")
else:
	print("Yes, we do.")		
#7-3	
number=input('\nPlease enter a number:')
number=int(number)
if number%10==0:
	print('This number is an integer multiple of ten.')
else:
	print('This number is not an integer multiple of ten.')
#7-4
pizza=' '
while pizza!='quit':
	pizza=input('What are the ingredients you need to add:')
	print("We're going to add "+pizza+" to the pizza")
#7-5
cinema_ticket=' '
while cinema_ticket!='quit':	
	cinema_ticket=input("What's your age, please")
	cinema_ticket=int(cinema_ticket)
	if cinema_ticket<3:
		print('Congratulations, you are free to watch!')
	elif cinema_ticket<12:
		print('Your ticket is ten dollars.')
	else:
		print('Your ticket is fifteen dollars.')
#7-6
active=True
while active:
	pizza=input('What are the ingredients you need to add:')
	if pizza=='quit':
		active=False
	else:
		print("We're going to add "+pizza+" to the pizza")
		break

active=True
while active:	
	cinema_ticket=input("What's your age, please")
	cinema_ticket=int(cinema_ticket)
	if cinema_ticket<3:
		print('Congratulations, you are free to watch!')
		active=False
	elif cinema_ticket<12:
		print('Your ticket is ten dollars.')
		active=False
	else:
		print('Your ticket is fifteen dollars.')
		active=False	
	break			
#7-7
x=1
while x<5:
	print(x)
#7-8	
sandwich_orders=['barbecue','chicken','cream']
finished_sandwiches=[]
while sandwich_orders:
    finished_sandwiche=sandwich_orders.pop()
    print('I made your '+finished_sandwiche+' sandwich')
    finished_sandwiches.append(finished_sandwiche)
for finished_sandwiche in finished_sandwiches:
	print(finished_sandwiche+' sandwich')
#7-9
sandwich_orders=['pastrami','barbecue','pastrami','chicken','cream','pastrami']
print('Pastrami pizza is sold out!')
while 'pastrami' in sandwich_orders:
	sandwich_orders.remove('pastrami')
print(sandwich_orders)
#7-10
responses={}
active=True
while active:
	name=input('\nWhat is your name?')
	city=input('If you could visit one place in the world, where would you go?')
	responses[name]=city
	repeat = input("Would you like to let another person respond? (yes/ no) ") 
	if repeat == 'no': 
		active = False
print("\n--- Poll Results ---") 
for name, city in responses.items(): 
	print(name + " wants to go to " + city + ".")
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值