python编程:从入门到实践 (第一版) 第七章学习笔记

第7章:用户输入和while 循环

input()
prompt = "If you tell us who you are, we can personlize the message you see."
prompt += "\nWhat is your first name?"

name = input(prompt)
print("Hello, " + name + "!")

注意: 通过input() 输入的值,默认为字符串类型

>>> age = input("How old are you?")
How old are you?20
>>> age
'20'
>>> age > 18
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: '>' not supported between instances of 'str' and 'int'

可以使用int() 函数,将字符串类型的值转为数值型

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

判断输入数值的奇偶

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!")
while 循环
示例
count = 1
while count <= 5:
    print(count)
    count += 1

输出:

1
2
3
4
5

可使用while 循环让程序在用户愿意时不断地运行,如下面的程序parrot.py所示。我们在其中定义了一个退出值,只要用户输入的不是这个值,程序就接着运行:
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)
    if message != 'quit':
        print(message)
使用标志
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 退出循环

要立即退出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() + " again.")
在循环中使用continue

要返回到循环开头,并根据条件测试结果决定是否继续执行循环,可使用continue 语句。(仅跳出单次循环)
示例:从1-10,只打印其中的偶数

# 我写的屎代码
number = 1
while number < 11:
    if number % 2 == 0:
        number += 1
        continue
    else:
        print(number)
        number += 1
# 书中代码
number = 0
while number < 10:
	number += 1
	if number % 2 == 0:
		continue
	print(number)
使用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())
删除包含特定值的所有列表元素
test_list = ['ttt', 'abc', 'def', 'ghi', 'ttt', 'kkk', 'ttt']
print(test_list)
while 'ttt' in test_list:
    test_list.remove('ttt')
print(test_list)
使用用户输入来填充字典

可使用while循环提示用户输入任意数量的信息。下面来创建一个调查程序,其中的循环每次执行时都提示输入被调查者的名字和回答。我们将收集的数据存储在一个字典中,以便将回答同被调查者关联起来

responses = {}

#设置一个标志,指出调查是否继续
active = True
while active:
    name = input("\nHello, what's your name?")
    response = input("Which mountain would you like to climb?")
    #将姓名和反馈存储到字典中
    responses[name] = response
    again = input("Would you like to let another person respond? (yes/ no) ")
    if again == 'no':
        active = False
for n, r in responses.items():
    print(n.title() + " would like to climb the " + r.title())
习题
7-1
car = input("Which car do you want to rent?")
print("Let me see if I can find you a " + car.title() + ".")
7-2
persons = input("How many people?")
persons = int(persons)
if persons > 8:
    print("We don't have  available talbe for " + str(persons) + ".")
else:
    print("We have  available table.")
7-3
number = input("Please enter a number: ")
number = int(number)
if number % 10 == 0:
    print(str(number) + " 是10的倍数。")
else:
    print(str(number) + " 不是10的倍数。")
7-4
prompt = "\n请输入一系列披萨配料:"
prompt += "\n输入'quit'退出程序。"
message = ""
while message != 'quit':
    message = input(prompt)
    if message != 'quit':
        print("我们会在披萨中添加" + message + "。")
7-5
age = input("How old are you?")
age = int(age)
if age < 3:
    price = 0
elif age < 12:
    price = 10
elif age >= 12:
    price = 15
print("You need pay for " + str(price) + "$.")
7-6

以7-4为例,7-4即为题目要求的第一种做法

#第二种做法
prompt = "\n请输入一系列披萨配料:"
prompt += "\n输入'quit'退出程序。"
active = True
while active:
    message = input(prompt)
    if message != 'quit':
        print("我们会在披萨中添加" + message + "。")
    else:
        active = False
#第三种做法
prompt = "\n请输入一系列披萨配料:"
prompt += "\n输入'quit'退出程序。"
while True:
    message = input(prompt)
    if message != 'quit':
        print("我们会在披萨中添加" + message + "。")
    else:
        break
7-7
number = 1
while number < 10:
	print(number)
7-8
sandwich_orders = ['鸡肉三明治', '火腿三明治', '素食三明治', '五香烟熏牛肉']
finished_sandwich = []
while sandwich_orders:
    finished = sandwich_orders.pop()
    print(finished + "已经做好了!")
    finished_sandwich.append(finished)
print("=================\n所有三明治订单已经完成:")
for sandwich in finished_sandwich:
    print(sandwich)
7-9
sandwich_orders = ['鸡肉三明治', '火腿三明治', '素食三明治', '五香烟熏牛肉', '五香烟熏牛肉', '五香烟熏牛肉']
finished_sandwich = []
print("店里的五香烟熏牛肉已经卖完了")
while '五香烟熏牛肉' in sandwich_orders:
    sandwich_orders.remove('五香烟熏牛肉')
while sandwich_orders:
    finished = sandwich_orders.pop()
    print(finished + "已经做好了!")
    finished_sandwich.append(finished)
if '五香烟熏牛肉' not in finished_sandwich:
    print("已完成的订单中没有五香烟熏牛肉")
print("=================\n已完成的三明治订单:")
for sandwich in finished_sandwich:
    print(sandwich)
7-10
# 使用用户输入填充字典
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值