阅读《Python编程从入门到实践》Day06

第七章

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

函数input()让程序暂停运行,等待用户输入一些文本。

message = input("Tell me something, and I will repeat it back to you: ")
print(message)
# 输出:
Tell me something, and I will repeat it back to you: python
python

括号中接收的参数就是向用户显示的提示或者说明,让用户知道该如何做。

(1)编写清晰的程序

使用input()函数时,最好指定清晰的提示,便于用户输入准确的信息。通常在提示的末尾再添加一个空格,以便区分提示与输入。当你需要指出获取特定输入的原因时,提示可能会很长,这时就可以将提示存储在一个变量中,然后再将变量传递给函数input()。

prompt = "If you tell us who you are, we can personlize the messages you see."
prompt += "\nWhat is your first name? "
name = input(prompt)
print(name)
# 输出:
If you tell us who you are, we can personlize the messages you see.
What is your first name? Jackson
Jackson

上述例子演示了一种创建多行字符串的方式,首先将前半部分字符串存储在一个变量中,然后使用运算符+=在原本字符串的末尾附加一个字符串。

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

使用函数input()时,Python将用户输入解读为字符串。

age = input("How old are you? ")
print(age)
print(type(age))
# 输出:
How old are you? 18
18
<class 'str'>

通过使用type()函数可以得知所输入的数值确实被当成了字符串类型。当你需要把它当成数字来使用时,就可以使用函数int(),它可以将数字字符串转换成数值。将数值输入用于计算和比较前,务必将其转换为数值表示。

(3)求模运算符

求模运算符(%)可以将两个数相除并返回余数。

print(10 % 3)
# 输出:
1
(4)在Python 2.7 中获取输入

如果你使用的是Python 2.7,应使用函数raw_input()来提示用户输入。这个函数与Python 3中的input()一样,也将输入解读为字符串。
Python 2.7也包含函数input(),但它将用户输入解读为Python代码,并尝试运行它们。因此,最好的结果是出现错误,指出Python不明白输入的代码;而最糟糕的结果是,将运行你原本无意运行的代码。所以如果你正在使用Python 2.7,请使用raw_input()来获取输入。

2、while循环简介

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

(1)使用while循环
current_number = 1
while current_number <= 5:
    print(current_number)
    current_number += 1
# 输出:
1
2
3
4
5

上述的循环例子中,表示当current_number的值小于等于5时,循环继续执行;当其大于5时,循环终止。

(2)让用户选择何时退出
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)
# 输出:

Tell me something, and I will repeat it back to you:
Enter 'quit' to end the program. Hello!
Hello!

Tell me something, and I will repeat it back to you:
Enter 'quit' to end the program. Python
Python

Tell me something, and I will repeat it back to you:
Enter 'quit' to end the program. quit

在上述的程序中,只有当你输入“quit”的时候,程序才会退出,否则程序会一直循环下去。

(3)使用标志

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

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)

在这个例子中添加了一个active标志,简化了while语句,因为不需要在其中做任何的比较,相关的逻辑由程序的其他部分处理。只要active的值为True,循环就会一直运行;而当程序运行到某一刻时将active的值改为了False,循环就终止。使用标志可以使得后期修改程序变得更简单容易。

(4)使用break退出循环

要立即退出while循环,不再运行循环中余下的代码,也不管条件测试的结果如何,可使用break语句。它用于控制程序流程。

prompt = "\nTell me something, and I will repeat it back to you:"
prompt += "\nEnter 'quit' to end the program. "
while True:
    message = input(prompt)
    if message == 'quit':
        break
    else:
        print(message)
# 输出:

Tell me something, and I will repeat it back to you:
Enter 'quit' to end the program. Hello
Hello

Tell me something, and I will repeat it back to you:
Enter 'quit' to end the program. quit

以True作为条件测试的while循环将不断运行,直到遇到break语句。在任何的Python循环中都可以使用break语句。

(5)在循环中使用continue

要返回到循环的开头,并根据条件测试结果决定是否继续执行循环,可使用continue语句,它与break不一样,它只是退出了当次的循环,然后继续执行下一次循环;而break是直接退出整个循环。

current_number = 0
while current_number < 10:
    current_number += 1
    if current_number % 2 == 0:
        continue
    print(current_number)
# 输出:
1
3
5
7
9

这里只输出了1到10之间的奇数,因为每当遇到偶数时都碰到了continue语句,使其退出了那一次的循环。

(6)避免无限循环

在while循环中,其中自增自减的语句时必不可少的,一旦写漏了,就会出现无限循环。要避免编写无限循环,务必对每个while循环进行测试,确保它按预期那样结束。

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

for循环是一种遍历列表的有效方式,但在for循环中不应修改列表,否则将导致Python难以跟踪其中的元素。要在遍历列表的同时对其进行修改,可使用while循环。

(1)在列表之间移动元素

使用一个while循环,在验证用户的同时将其从未验证用户用户列表中提取出来,再将其加入到另一个已验证用户列表中。

unconfirm_users = ['alice', 'brian', 'candace']
confirm_users = []
while unconfirm_users:
    current_user = unconfirm_users.pop()
    print("Verifying user: " + current_user.title())
    confirm_users.append(current_user)
print("\nThe following users have been confirmed: ")
for confirm_user in confirm_users:
    print(confirm_user.title())
# 输出:
Verifying user: Candace
Verifying user: Brian
Verifying user: Alice

The following users have been confirmed: 
Candace
Brian
Alice
(2)删除包含特定值的所有列表元素

我们已经知道remove()可以删除列表中与之匹配的第一个元素,而当有多个相同的元素出项在列表中时,可以使用while循环来删除所有特定的值。

pets = ['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']
print(pets)
while 'cat' in pets:
    pets.remove('cat')
print(pets)
# 输出:
['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']
['dog', 'dog', 'goldfish', 'rabbit']
(3)使用用户输入来填充字典

使用while循环来创建一个调查程序,并将收集的数据存储在一个字典中,用户的名字就是键,用户的回答就是值。最后打印调查结果。

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(name + " would like to climb " + response + ".")
# 输出:
What is your name? Eric
Which mountain would you like to climb someday? Denali
Would you like to let another person respond?(yes/no) yes

What is your name? Lynn
Which mountain would you like to climb someday? Devil's Thumb
Would you like to let another person respond?(yes/no) no

--- Poll Result ---
Eric would like to climb Denali.
Lynn would like to climb Devil's Thumb.
    原文作者:晓梅_aa3b
    原文地址: https://www.jianshu.com/p/c9420ec082ee
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞