Python基础入门知识(6)

接前面的文章:
Python基础入门知识(1)
Python基础入门知识(2)
Python基础入门知识(3)
Python基础入门知识(4)
Python基础入门知识(5)

2 Python的基础知识

2.12 用户输入和while循环

2.12.1 函数input()的工作原理

在实际开发中会遇到需要获取信息的一些情况,如表单中的用户名、年龄等,这时就会用到函数input()。
函数input()会让程序暂停运行,等待用户输入一些文本。获取用户输入后,Python将其存储在一个变量中,以方便我们使用。
例如,下面的程序让用户输入一些文本,再将这些文本呈现给用户:

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:

我们在后面输入“hello”试试。

Tell me something, and I will repeat it back to you:hello
hello
2.12.1.1 编写清晰的程序

值得注意的是,当我们使用函数input()时,应该给出清晰易懂的提示,准确地指出我们希望用户提供什么样的信息——指出用户该输入任何信息的提示都行,如下所示:

name = input("Please enter your name: ")
print("Hello, "+name+"!")

输出:

Please enter your name: Shirley
Hello, Shirley!

如果提示超过一行,可将提示存储在一个变量中,再将该变量传递给函数input()。这样,即便提示超过一行,input()语句也非常清晰。
例如:

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("\nHello, "+name+"!")

输出:

If you tell us who you are, we can personalize the messages you see.
What is your first name?

这里我们用了一种创建多行字符串的方式。第1行将消息的前半部分存储在变量prompt中;在第2行中,运算符+=在存储在prompt中的字符串末尾附加一个字符串。

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

使用函数input()时,Python将用户输入的内容解读为字符串。但如果要输入的是数字,怎么办?
为解决这个问题,可使用函数int(),它让Python将输入视为数值。函数int()将数字的字符串表示转换为数值表示,如下所示:

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

在这个示例中,我们在提示时输入21后,Python将这个数字解读为字符串,但随后int()将这个字符串转换成了数值表示。这样Python就能运行条件测试了:将变量age(它现在包含数值21)同18进行比较,看它是否大于或等于18。测试结果为True。
如何在实际程序中使用函数int()呢?请看下面的程序,它判断一个人是否满足坐过山车的身高要求:

height = input("How tall are you, in inches? ")
height = int(height)
if height >= 36:
    print("\nYou're tall enough to ride!")
else:
    print("\nYou'll be able to ride when you're a little older.")

输出:

How tall are you, in inches? 71

You're tall enough to ride!
2.12.1.3 求模运算符

处理数值信息时,求模运算符(%)是一个很有用的工具,它将两个数相除并返回余数。如果一个数可被另一个数整除,余数就为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("\nThe number "+str(number)+" is even. ")
else:
    print("\nThe number "+str(number)+" is odd.")

输出:

Enter a number, and I'll tell you if it's even or odd:42

The number 42 is even. 

2.12.2 while循环简介

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

2.12.2.1 使用while循环

例如,我们用while循环从1数到5:

current_number = 1
while current_number <= 5:
    print(current_number)
    current_number += 1

首先,我们设定current_number为1,从而指定从1开始数。
然后,设置while循环current_number小于或等于5,就可以运行这个循环。
接着,打印current_number的值。
再使用代码current_number+= 1将其值加1,只要满足条件current_number <= 5,Python就接着运行这个循环。
循环结束后,输出:

1
2
3
4
5
2.12.2.2 让用户选择何时退出

可使用while循环让程序在用户愿意时不断地运行,如下面的程序:
我们在其中定义了一个退出值,只要用户输入的不是这个值,程序就接着运行。

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)

我们定义了一条提示消息,告诉用户他有两个选择:要么输入一条消息,要么输入退出值(这里为’quit’)。
输出如下:

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

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

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

这个程序很好,唯一美中不足的是,它将单词’quit’也作为一条消息打印了出来。为修复这种问题,只需使用一个简单的if测试:

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 everyone!
Hello everyone!

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

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

我们发现这时再退出,不再打印“quit”了。

2.12.2.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设置成True,让程序最初处于活动状态。这样做简化了while语句,因为不需要在其中做任何比较——相关的逻辑由程序的其他部分处理。只要变量active为True,循环就将继续运行。

2.12.2.4 使用break退出循环

要立即退出while循环,不再运行循环中余下的代码,也不管条件测试的结果如何,可使用break语句。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()+"!")

这个程序中的循环不断输入用户到过的城市的名字,直到他输入’quit’为止。用户输入’quit’后,将执行break语句,导致Python退出循环:

Please enter the name of a city you have visited.
(Enter 'quit' when you are finished.)shanghai
I'd love to go to Shanghai!

Please enter the name of a city you have visited.
(Enter 'quit' when you are finished.)quit
2.12.2.5 在循环中使用continue

要返回到循环开头,并根据条件测试结果决定是否继续执行循环,可使用continue语句,它不像break语句那样不再执行余下的代码并退出整个循环。
例如,来看一个从1数到10,但只打印其中奇数的循环:

current_number = 0
while current_number < 10:
    current_number += 1
    if current_number % 2 ==0:
        continue
    print(current_number)

输出:

1
3
5
7
9
2.12.2.6 避免无限循环

每个while循环都必须有停止运行的途径,这样才不会没完没了地执行下去。
例如,下面的循环从1数到5:

x = 1
while x <= 5:
    print(x)
    x += 1

输出:

1
2
3
4
5

但如果我们不小心遗漏了代码行x+= 1,这个循环将没完没了地运行:

x = 1
while x <= 5:
    print(x)

输出:

1
1
1
1
1
1
1
...

每个程序员都会偶尔因不小心而编写出无限循环,在循环的退出条件比较微妙时尤其如此。如果程序陷入无限循环,可按Ctrl+C,也可关闭显示程序输出的终端窗口。

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

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

2.12.3.1 在列表之间移动元素

假设有一个列表,其中包含新注册但还未验证的网站用户;验证这些用户后,如何将他们移到另一个已验证用户列表中呢?一种办法是使用一个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())

为模拟用户验证过程,我们打印一条验证消息并将用户加入到已验证用户列表中。未验证用户列表越来越短,而已验证用户列表越来越长。未验证用户列表为空后结束循环,再打印已验证用户列表,输出:

Verifying user: Candace
Verifying user: Brian
Verifying user: Alice

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

在之前,我们使用函数remove()来删除列表中的特定值,这之所以可行,是因为要删除的值在列表中只出现了一次。如果要删除列表中所有包含特定值的元素,该怎么办呢?
假设我们有一个宠物列表,其中包含多个值为’cat’的元素。要删除所有这些元素,可不断运行一个while循环,直到列表中不再包含值’cat’,如下所示:

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']

我们可以看到,‘cat’在这个列表中不见了。

2.12.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 Results ---")
for name, response in responses.items():
    print(name+" would like to climb "+response+".")

首先,我们定义了一个空字典(responses)。
接着,我们设置了一个标志(polling_active),用于指出调查是否继续。只要polling_active为True,Python就运行while循环中的代码。
然后,在while循环中,提示用户输入其用户名及其喜欢爬哪座山。
再然后,将这些信息存储在字典responses中,然后询问用户调查是否继续。
如果用户输入yes,程序将再次进入while循环;如果用户输入no,标志polling_active将被设置为False,而while循环将就此结束。
最后,打印显示调查结果。

输出:

What is your name? Shirley
Which mountain would you like to climb someday?Huangshan
Would you like to let another person respond? (yes/ no) yes

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

--- Poll Results ---
Shirley would like to climb Huangshan.
Lynn would like to climb Taishan.

后续更新:
Python基础入门知识(7)

  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值