目录
- 一、input输入函数
- 实例
- 二、while循环
- 2.1 while结构
- 练习题
- 2.2 使用while循环处理列表和字典
- 2.2.1 在列表之间移动元素
- 2.2.2 删除为特定值的多个列表元素
- 2.2.3 使用用户输入来填充字典
- 练习题
一、input输入函数
input( ) 方法:获取用户的输入信息,使用函数input() 时,Python将用户输入解读为字符串。
如果想要将input输入的字符串转换成需要的变量类型(如整型int),则可以使用int()函数进行类型转换。
实例
- 让用户输入自己的年龄,并且判断是否为成年人(>=18岁)
age = input("Please input your age :")
age = int(age)
if age >= 18:
print("You are an adult now!")
else:
print("You need tu grow up!")
- 让用户输入一个数,并指出该数是否是10的整数倍。
number = int(input("Please input an integer: "))
if number%10==0:
print("This number is a multiple of ten.")
else:
print("This number is not a multiple of ten.")
二、while循环
2.1 while结构
练习题
7-4
使用break关键词结束循环。
prompt = "Please enter the topping of pizza: "
prompt += "(Enter 'quit' when you are finished.)"
while True:
topping = input(prompt)
if topping == 'quit':
print("exit")
break
else:
print(f"We are gonna put {topping} into your pizza.")
7-5
使用flag标记结束循环。
flag = True
while flag:
age = input("Input the age (Enter quit to end this program) : ")
if age == 'quit':
flag = False
else:
age = int(age)
if age < 3:
print("free.")
elif age >= 3 and age <= 12:
print("charge 10.")
else:
print("charge 15.")
2.2 使用while循环处理列表和字典
2.2.1 在列表之间移动元素
假设有一个列表包含新注册但还未验证的网站用户,验证这些用户后,将他们从原列表中删除,然后添加到另一个已验证用户列表中。
- 因为题目要求要将验证后的用户名称从原列表中删除,说明列表是需要动态变化的,所以不能使用for循环进行对原列表的遍历,可以使用while循环对列表进行判断,结束条件即为列表为空时。
- 在while循环中,使用pop方法把原有列表中的元素弹出,然后使用append方法添加进新列表中,当原列表中所有元素都被弹出时(列表为空),则结束循环。
unconfirmed_users = ['jack','alice','will','mary']
confirmed_users = []
while unconfirmed_users:
current_user = unconfirmed_users.pop()
print(f"Verifying user: {current_user.title()}")
confirmed_users.append(current_user)
print("The following users have been confirmed: ")
for confirmed_user in confirmed_users:
print(confirmed_user.title())
2.2.2 删除为特定值的多个列表元素
当列表中有多个相同的元素并且需要把他们都删除时,单独使用remove无法实现,因此使用while循环,当还有该元素在列表中时,就一直执行remove操作。
pets = ['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']
print(pets)
while 'cat' in pets:
pets.remove('cat')
print(pets)
2.2.3 使用用户输入来填充字典
创建一个调查程序,其中的循环每次执行时都提示输入用户的名字和年龄。将收集的数据存储在一个字典中。
- 使用flag标志进行循环是否结束的判断
responses = {}
flag = True
while flag:
name = input("What's your name? ")
age = int(input("How old are you? "))
responses[name] = age
repeat = input("Would you like to let another person respond? (yes/ no) ")
if repeat=='no':
flag=False
print("Results")
for name,age in responses.items():
print(f"{name} is {age} years old.")
练习题
7-8
sandwich_orders=["Black Forest Ham","Chicken & Bacon Ranch Melt","Cold Cut Combo"
,"Italian B.M.T.","Meatball Marinara","Oven Roasted Chicken","Veggie Delite"]
finished_snadwiches=[]
while sandwich_orders:
sandwich_being_made = sandwich_orders.pop()
print(f"I made your {sandwich_being_made} Sandwich.")
finished_snadwiches.append(sandwich_being_made)
for finished_snadwich in finished_snadwiches:
print(finished_snadwich)
7-9
print("Sorry, we have already sold all the pastrami!")
sandwich_orders=["Black Forest Ham","pastrami","Chicken & Bacon Ranch Melt",
"Cold Cut Combo","Italian B.M.T.","pastrami",
"Meatball Marinara","Oven Roasted Chicken",
"pastrami","Veggie Delite"]
print(sandwich_orders)
while 'pastrami' in sandwich_orders:
sandwich_orders.remove('pastrami')
finished_snadwiches=[]
while sandwich_orders:
sandwich_being_made = sandwich_orders.pop()
print(f"I made your {sandwich_being_made} Sandwich.")
finished_snadwiches.append(sandwich_being_made)
print(finished_snadwiches)
7-10
flag = True
results = {}
while flag:
name = input("Please enter your name: (Enter exit to end this program.)")
if name == 'exit':
print("exit")
flag = False
else:
place = input("If you could visit one place in the world, where would you go? ")
results[name]=place
for name,place in results.items():
print(f"{name.title()} wanna go {place.title()}!")