Python第七章
Posted xdz-toptan
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python第七章相关的知识,希望对你有一定的参考价值。
第 7 章 用户输入和while循环
7.1 函数input()的工作原理
message = input("Tell me something, and I will repeat it back to you: ")
print(message)
7.1.1 编写清晰的程序
name = input("Please enter your name: ")
print("Hello, " + name + "!")
prompt = "If you tell us who you are, we can personalize the message you see."
prompt += " What is your first name? "
name = input(prompt)
print(" Hello, " + name + "!")
7.1.2 使用int()来获取数值输入
age = input("How old are you? ")
print("I‘m " + str(age) + ".") # 可转化为字符串再打印输出,间接的赋值数字必须转化为字符串再输出打印,否则打印会出错
print("I‘m " + age + ".") # 输入的数字age为字符串可直接打印
age = input("How old are you? ") # 此处age为字符串,需用int()转换为数字才能跟数字比较大小
age >= 18
age = input("How old are you? ")
age = int(age)
if age >= 18:
print("Yes!")
判断一个人是否满足坐过山车的身高要求
height = input("How tall are you, in inches? ")
height = int(height)
if height >= 36:
print(" You ‘re tall enough to ride!")
else:
print(" You‘ll be able to ride when you‘re a little older.")
7.1.3 求模运算符
a = 4 % 3
print(a)
b = 5 % 3
print(b)
c = 6 % 3
print(c)
如果一个数可被另一个数整除,余数就为0,因此求模运算符将返回0。
你可利用这一点来判断一个数是奇数还是偶数。
number = input("Enter a number, and I‘ll tell you if it‘s even or odd: ")
number = int(number)
if number % 2 == 0:
print(" The number " + str(number) + " is even.")
else:
print(" The number " + str(number) + " is odd.")
如果你使用的是Python 2.7,应使用函数raw_input() 来提示用户输入。这个函数与Python 3中的input() 一样,也将输入解读为字符串。
7-1 汽车租赁
car = input("What kind of car would you like? ")
print("Let me see if I can find you a " + car.title() + ".")
7-2 餐馆订位
number = input("How many people are in your dinner party tonight? ")
number = int(number)
if number > 8:
print("I‘m sorry, you‘ll have to wait for a table.")
else:
print("Your table is ready.")
7-3 10的整数倍
number = input("Please enter a number: ")
number = int(number)
if number % 10 == 0:
print(str(number) + " is a multiple of 10.")
else:
print(str(number) + " is not a multiple of 10.")
7.2.1 使用while循环
current_number = 1
while current_number <= 5:
print(current_number)
current_number += 1 # current_number = current_number + 1
7.2.2 让用户选择何时退出
prompt = " Tell me something, and I will repeat it back to you:"
prompt += " Enter ‘quit‘ to end the program."
message = ""
while message != ‘quit‘:
message = input(prompt)
print(message)
prompt = " Tell me something, and I will repeat it back to you:"
prompt += " Enter ‘quit‘ to end the program."
message = ""
while message != ‘quit‘:
message = input(prompt)
if message != ‘quit‘:
print(message)
7.2.3 使用标志
prompt = " Tell me something, and I will repeat it back to you:"
prompt += " Enter ‘quit‘ to end the program. "
active = True
while active:
message = input(prompt)
if message == ‘quit‘:
active = False
else:
print(message)
7.2.4 使用break 退出循环
注意 在任何Python循环中都可使用break 语句。例如,可使 用break 语句来退出遍历列表或字典的for 循环。
prompt = " Please enter the name of a city you have visited:"
prompt += " (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() + ".")
7.2.5 在循环中使用continue
current_number = 0
while current_number < 10:
current_number += 1
if current_number % 2 == 0:
continue
print(current_number)
7.2.6 避免无限循环
x = 1
while x <= 5:
print(x)
x += 1 # 没这句程序会无限循环下去
7-4 披萨配料
prompt = " What topping would you like on your pizza?"
prompt += " Enter ‘quit‘ when you are finished: "
while True:
topping = input(prompt)
if topping != ‘quit‘:
print(" I will add " + topping + " to your pizza.")
else:
break
7-5 电影票
prompt = " How old are you? We will tell you the prize."
prompt += " Enter ‘quit‘ when you are finished. "
while True:
age = input(prompt)
if age == ‘quit‘:
break
age = int(age)
if age < 3:
print(" You get in free!")
elif age < 12:
print(" Your ticket is 10 dollars.")
else:
print(" Your ticket is 15 dollars.")
7-6 三个出口
prompt = " What topping would you like on your pizza?"
prompt += " Enter ‘quit‘ when you are finished: "
active = True
while active:
topping = input(prompt)
if topping != ‘quit‘:
print(" I will add " + topping + " to your pizza.")
else:
active = False
7.3.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("
The following users have been confirmed:")
for confirmed_user in confirmed_users:
print(confirmed_user.title())
7.3.2 删除包含特定值的所有列表元素
pets = [‘dog‘, ‘cat‘, ‘dog‘, ‘goldfish‘, ‘cat‘, ‘rabbit‘, ‘cat‘]
print(pets)
while ‘cat‘ in pets:
pets.remove(‘cat‘)
print(pets)
7.3.3 使用用户输入来填充字典
responses = {}
设置一个标志,指出调查是否继续
polling_active = True
while polling_active:
# 提示输入被调查者的名字和回答
name = input(" What 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 response? (yes/no) ")
if repeat == ‘no‘:
polling_active = False
# 调查结束,显示结果
print(" --- Poll Results ---")
for name, response in responses.items():
print(name.title() + " would like to climb " + response.title() + ".")
7-8 熟食店
sandwich_orders = [‘tuna‘, ‘veggie‘, ‘grilled cheese‘, ‘turkey‘, ‘roast beef‘]
finished_sandwiches = []
for sandwich in sandwich_orders:
print("
I made your " + sandwich + " sandwich.")
finished_sandwiches.append(sandwich)
print("Here are the finished sandwiches:")
for sandwich in finished_sandwiches:
print(sandwich)
sandwich_orders = [‘tuna‘, ‘veggie‘, ‘grilled cheese‘, ‘turkey‘, ‘roast beef‘]
finished_sandwiches = []
while sandwich_orders:
current_sandwich = sandwich_orders.pop()
print("I‘m working on your " + current_sandwich + " sandwich.")
finished_sandwiches.append(current_sandwich)
print("
")
for sandwich in finished_sandwiches:
print("I made a " + sandwich + " sandwich.")
7-9 五香烟熏牛肉(pastrami)卖完了
sandwich_orders = [‘pastrami‘, ‘tuna‘, ‘pastrami‘, ‘veggie‘, ‘grilled cheese‘, ‘pastrami‘, ‘turkey‘, ‘roast beef‘]
finished_sandwiches = []
print("I‘m sorry, we‘re all out of pastrami today.")
while sandwich_orders:
current_sandwich = sandwich_orders.pop()
if current_sandwich != ‘pastrami‘:
finished_sandwiches.append(current_sandwich)
print("I‘m working on your " + current_sandwich + " sandwich.")
print("
")
for sandwich in finished_sandwiches:
print("I made a " + sandwich + " sandwich.")
sandwich_orders = [‘pastrami‘, ‘tuna‘, ‘pastrami‘, ‘veggie‘, ‘grilled cheese‘, ‘pastrami‘, ‘turkey‘, ‘roast beef‘]
finished_sandwiches = []
print("I‘m sorry, we‘re all out of pastrami today.")
while ‘pastrami‘ in sandwich_orders:
sandwich_orders.remove(‘pastrami‘)
print("
")
while sandwich_orders:
current_sandwich = sandwich_orders.pop()
print("I‘m working on your " + current_sandwich + " sandwich.")
finished_sandwiches.append(current_sandwich)
print("
")
for sandwich in finished_sandwiches:
print("I made a " + sandwich + " sandwich.")
7-10 梦想的度假胜地
responses = {}
name_prompt = "
What‘s your name? "
place_prompt = "If you want to visit one place in the world, what would it be? "
continue_prompt = "
Would you like to let someone else respond? (yes/no) "
while True:
name = input(name_prompt)
place = input(place_prompt)
responses[name] = place
repeat = input(continue_prompt)
if repeat != ‘yes‘:
break
print("
--- Results ---")
for name, place in responses.items():
print(name.title() + " would like to visit " + place.title() + ".")
以上是关于Python第七章的主要内容,如果未能解决你的问题,请参考以下文章