《Python从入门到实践》读书笔记——第七章 用户输入和whIle循环

《Python从入门到实践》读书笔记——第七章 用户输入和whIle循环

1. 函数 input() 的工作原理

函数 input() 让程序暂停运行, 等待用户输入一些文本. 获取用户输入后, Python将其赋给一个变量, 以方便你使用.

message = input("Tell my something, and I will repeat it back to you: ")
print(message)

函数 input() 接受一个参数 – 要向用户显示的 提示 或 说明, 让用户知道该如何做.

  • 有时候, 提示可能超过一行. 例如, 你可能需要指出获取特定输入的原因. 在这种情况下, 可将提示赋值个一个变量, 再将变量传递给函数 input() . 这样, 即便提示超过一行, inpput() 语句也会非常清晰.
prompt = "If you tell us who you are, we can personalize the messages you see."
prompt += "\nWhat is your first name? "

name = input(prompt)
print(f"\nHello, {name}!")
  • 本例中演示了一种 创建多行字符串 的方式. 第一行将消息的前半部分赋给变量 prompt 中. 在第二行中, 运算符+= 在前面赋给变量 prompt 的字符串末尾附加一个字符串
    • 最终的提示占据两行, 且问号后面有一个空格, 这也是为了使其更加清晰.

1.1 使用 int() 来获取数值输入

使用 input() 时, Python将用户输入解读为字符串,如果将输出作为数来使用,会引发错误
为解决这个问题, 可使用函数 int() , 它让Python将输入视为数值. 函数 int() 将数的字符串转换为数值表示

>>> age = input("How old are you? ")
How old are you? 21
>>> age = int(age)
>>> age >= 18
True
height = input("How tall are you, in inches? ")
height = int(height)

if height >= 48:
    print("\nYou're tall enough to ride!")
else:
    print("\nYou'll be able to ride when you're a litter older")

1.2 求摸运算符

>>> 4 % 3
1
>>> 5 % 3
2
>>> 6 % 3
0
>>> 7 % 3
1
# 判断一个数是奇数还是偶数
number = input("Enter a number, and I'll tell you if it's even or odd: ")
number = int(number)

if number % 2 ==0:
    print(f"\nThe number {number} is even.")
else:
    print(f"\nThe number {number} is odd.")

2. while循环

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

2.1 使用while循环

current_number = 1
while current_number <= 5:
    print(current_number)
    current_number += 1
    
#
1
2
3
4
5

2.2 让用户选择何时退出

# 定义了一个退出值, 只要用户输出的不是这个值, 程序就继续运行
prompt = "\nTell me something, and I will repeat it back to you:"
prompt += "\nEnter 'quit' to end thr program. "
message = ""
while message != 'quit':
    message = input(prompt)
    if message != 'quit':
        print(message)

2.3 使用标志

在很多条件都满足才继续运行的程序中, 可定义一个变量, 用于判断整个程序是否处于活动状态. 这个变量称为 标志 , 充当程序的交通信号灯. 可以让程序在标志为 True 时继续运行, 并在任何事件导致表示的值为 False 时让程序停止运行. 这样, 在while语句中就只需要检查一个条件 : 标志的当前值是否为 True. 然后将所有其他测试(是否发生了应将标志设置为False的时间)都放在其他地方,从而让程序更整洁.

# 在钱一节的程序中添加一个标志, 将其命名为 active(你可以给它指定任何名称), 用于判断程序是否继续运行:
prompt = "\nTell me something, and I will repeat it back to you:"
prompt += "\nEnter 'quit' to end thr program. "

active = True
while active:
    message = input(prompt)

    if message == 'quit':
        active = False
    else:
        print(message)

2.4 使用 break 退出循环

立即退出while循环,不再运行循环中余下的代码,也不管条件测试的结果如何,可使用 break 语句

# 在钱一节的程序中添加一个标志, 将其命名为 active(你可以给它指定任何名称), 用于判断程序是否继续运行:
prompt = "\nTell me something, and I will repeat it back to you:"
prompt += "\nEnter 'quit' to end thr program. "

while True:
    message = input(prompt)

    if message == 'quit':
        break
    else:
        print(message)

在任何Python循环中都可以使用break语句. 例如, 可使用break语句来退出遍历列表或字典的for循环

2.5 在循环中使用 continue

要返回循环开头, 并根据条件测试结果决定是否继续执行循环, 可使用 continue 语句

# 从1数到10但只打印其中的奇数的循环
current_number = 0
while current_number < 10:
    current_number += 1
    if current_number % 2 == 0:
        continue
    print(current_number)

2.6 避免无限循环

每个while循环都必须有停止运行的途径, 这样才不会没完没了地执行下去.
如果程序陷入无限循环, 可按 Ctrl + C, 也可关闭显示程序输出的终端窗口

要避免编写无限循环, 无比对每个while循环进行测试, 确保按预期那样结束.

3. 使用while循环处理列表和字典

要记录大量的用户和信息, 需要在while循环中使用列表和字典.

for循环是一种遍历列表的有效方法, 但不应该在for循环中修改列表, 否则将导致Python难以跟踪其中的元素. 要在 遍历列表的同时对其进行修改 , 可使用while循环. 通过将while循环同列表和字典结合起来使用, 可收集、存储 并组织大量输入, 供以后查看和显示.

3.1 在列表之间移动元素

# 首先,创建一个待验证用户列表
#   和一个用于存储已验证用户的空列表.
unconfirmed_users = ['alice', 'brain', 'candace']
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())

首先创建一个未验证用户列表, 其中包含用户 Alice, Brian 和 Candace, 还创建了一个空列表, 用于存储已验证的用户. while循环将不断运行, 直到列表 unconfirmed_users 变成空的. 在此循环中, 方法 pop() 以每次一个的方式从列表 unconfirmed_users 末尾删除未验证的用户. 由于Candace位于列表末尾, 其名字 首先 被删除, 赋给变量 current_user 并加入列表 confirmed_users 中. 接下来是Brain, Alice.
为模拟用户验证过程, 我们打印一条验证消息并将用户加入已验证用户列表中. 未验证用户列表越来越短, 而已验证用户越来越长. 未验证用户列表为空后结束循环, 再打印已验证用户列表:

Verifying user: Candace
Verifying user: Brain
Verifying user: Alice

The following users have been confirmed:
Candace
Brain
Alice

3.2 删除为特定值的所有列表元素

pets = ['dog', 'cat', 'dog', 'godfish', 'cat', 'rabbit', 'cat']
print(pets)

while 'cat' in pets:
    pets.remove('cat')

print(pets)

#
['dog', 'cat', 'dog', 'godfish', 'cat', 'rabbit', 'cat']
['dog', 'dog', 'godfish', 'rabbit']

3.3 使用用户输入来填充字典

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 Result---")
for name, response in responses.items():
    print(f"{name} would like to climb {response}.")
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值