今天复习了用户输入和while循环。最近迷上了秦汉历史,看的欲罢不能。
1.用户输入
parrot.py
message = input("Tell me something,and I will repeat it back to you: ")
print(message)
greeter.py
prompt = "If you share your name,we can personalize the messages you see."
prompt +="\nWhat is your first name? " #"+="创建多行字符串
name = input(prompt)
print(f"\nHello, {name}!")
- str 转换成整数格式:int()
- 求模运算符:% 相除返回余数
练习
汽车租赁
car=input("Which car would you like to buy? ")
print(f"Let me see if I can find you a {car.title()}.")
2.while 循环
counting.py
current_number = 1
while current_number <= 5:
print(current_number)
current_number +=1
parrot.py
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)
- 对于多个条件控制的循环,为了让程序更便于阅读和理解,通常会定义变量为标志(flag),这样只需要判定flag的True或者False即可。 parrot.py2.0
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退出循环 cities.py
prompt = "\nPlease enter the name of a city you have visited:"
prompt +="\n(Enter 'quit' when you are finished.)"
while True: # while True 会一直执行,直到遇到break
city = input(prompt)
if city == "quit":
break
else:
print(f"I'd love to go to {city.title()}!")
- 使用continue继续执行 counting.py
current_number = 0
while current_number < 10:
current_number += 1
if current_number % 2 == 0:
continue
print(current_number)
pizza.py
peil = "\nPlease tell me what do you want to add to the pizza? "
peil +="\nInput quit anytime you want to quit."
while True:
pi=input(peil)
if pi == "quit":
break
else:
print(f"\nYou want to add {pi.title()} in the pizza.")
电影票价
contempt="\nPlease tell me how old are you? "
while True:
age=input(contempt)
try:
age_int=int(age)
if 0 < age_int < 3:
print("You are under 3 so you are free.")
elif age_int < 12:
print("You need to pay 10 dollars for the ticket.")
elif age_int < 130:
print("You need to pay 15 dollars for the ticket.")
except ValueError:
print("Please input a valid number.")
break
contempt="\nPlease tell me how old are you? "
contempt += "\nEnter 'quit' to exit."
active = True
while active:
age=input(contempt)
if age == "quit":
active = False
else:
try:
age_int=int(age)
if age_int < 3:
print("You are under 3 so you are free.")
elif age_int < 12:
print("You need to pay 10 dollars for the ticket.")
elif age_int < 130:
print("You need to pay 15 dollars for the ticket.")
except ValueError:
print("Please enter a valid number!")
- 处理列表或字典(不用for循环修改列表,因为会导致python难以跟踪其中的元素,如前面的例题中所出现的) 验证客户列表:confirmed_users.py
#首先创建一个待验证用户列表
#和一个用于存储已验证用户的空列表
unconfirmed_users = ['alice','coco','cai']
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())
- 删除为特定值的所有列表元素 pets.py
pets = ['dog','cat','fish','dog','cat','parrot']
print(pets)
while 'cat' in pets:
pets.remove('cat')
print(pets)
- 使用用户输入填充字典 mountain_poll.py
responses={}
#设置一个标志,指出调查是否继续
polling_active = True
while polling_active:
#提升输入被调查者的名字和回答
name=input("\nWhat is your name? ")
response=input("\nWhich moutain 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}.")
练习
- 三明治店
# 创建列表
sandwich_orders = ['sand_a','sand_b','sand_c']
finished_sandwiches = []
active = True
while active:
if sandwich_orders:
san=sandwich_orders.pop()
print(f"I made your {san} sandwich. ")
finished_sandwiches.append(san)
break
print("\nThe following sandwiches had been made for you: ")
for san_f in finished_sandwiches:
print(f"\t{san_f}")
# 创建列表
sandwich_orders = ['sand_a','sand_b','sand_c']
finished_sandwiches = []
active = True
while active:
if sandwich_orders: # 4个空格
san = sandwich_orders.pop() # 8个空格(4+4)
print(f"I made your {san} sandwich. ") # 8个空格
finished_sandwiches.append(san) # 8个空格
print(finished_sandwiches) # 8个空格
else: # 4个空格
active = False # 8个空格
# break # 或者用break退出循环
print("\nThe following sandwiches had been made for you: ")
for san_f in finished_sandwiches: # 4个空格
print(f"\t{san_f}") # 8个空格
- 五香牛肉
# 创建列表
sandwich_orders = ['sand_a','sand_b','sand_c','pastrami','pastrami','pastrami']
print("The pastrami has sold out")
active = True
while active:
if 'pastrami' in sandwich_orders:
sandwich_orders.remove('pastrami')
else:
active = False
# break # 或者用break退出循环
for san_f in sandwich_orders:
print(f"\t{san_f}")
- 想去的地方
responses={}
active=True
while active:
name=input("\nWhat is your name? ")
place=input("\nIf you could visit one place in the world,where would you go? ")
responses[name]=place
repeat=input("\nIs there anyone you want to let him answer the question? ""yes/no")
if repeat == 'no':
active = False
print("\n--- Poll Results ---")
for name, place in responses.items():
print(f"{name} would like to go to {place}.")