0%

第七章 用户输入和while循环

7.1 函数input()的工作原理

1
2
message = input("tell me something:")
print(message)

输出结果为:

1
2
tell me something:Hello Python World!   #Hello Python World!为用户在控制台的输入
Hello Python World!

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

程序运行到input()函数时,程序等待用户输入,并在用户按回车键后继续运行。

7.1.1 编写清晰的程序

有时候,提示可能超过一行。例如,你可能需要指出获取特定输入的原因。在这种情况下,可将提示赋给一个变量,再将该变量传递给函数input()。这样,即便提示超过一行,input()语句也会非常清晰。

1
2
3
4
prompt = "If you tell us who you are, we can personalize the message you see."
prompt += "\nWhat is your first name?"
name = input(prompt)
print(f"hello, {name}!")

输出结果为:

1
2
3
If you tell us who you are, we can personalize the message you see.
What is your first name?zhang
hello, zhang!

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

使用函数input()时,Python将用户输入解读为字符串。为解决这个问题,可使用函数int(),它让Python将输入视为数值。函数int()将数的字符串转换为数值表示:

1
2
3
4
age = input("How old are you?")
age = int(age)
if(age >= 18):
print("you are a men!")

输出结果为:

1
2
How old are you?24
you are a men!

还有函数float()可将字符串转为小数。

7.1.3 求模运算符

处理数值信息时,求模运算符(%)是个很有用的工具,它将两个数相除并返回余数:

1
2
3
4
print(4 % 3)
print(5 % 3)
print(6 % 3)
print(7 % 3)

输出结果为:

1
2
3
4
1
2
0
1

7.2 while循环简介

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

7.2.1 使用while循环

1
2
3
4
cur_number = 1
while cur_number < 6:
print(cur_number)
cur_number += 1

输出结果为:

1
2
3
4
5
1
2
3
4
5

7.2.2 让用户选择何时退出

可以使用while循环让程序在用户愿意时不断运行,可以定义一个退出值,只要用户输入的不是这个值,程序就将接着运行:

1
2
3
4
5
message = ""
while message != 'quit':
message = input("please input something:")
if message != 'quit':
print(f"your input the message is :{message}")

输出结果为:

1
2
3
4
5
6
7
8
9
10
please input something:hello
your input the message is :hello

please input something:python
your input the message is :python

please input something:world
your input the message is :world

please input something:quit

7.2.3 使用标志

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

1
2
3
4
5
6
7
8
message = ""
flag = True
while flag:
message = input("please input something:")
if message != 'quit':
print(f"your input the message is :{message}")
else:
flag = False

输出结果为:

1
2
3
4
5
6
7
8
9
10
please input something:hello 
your input the message is :hello

please input something:python
your input the message is :python

please input something:world
your input the message is :world

please input something:quit

7.2.4 使用break退出循环

break语句用于控制程序流程,可用来控制哪些代码行将执行,哪些代码行不执行,从而让程序按你的要求执行你要执行的代码。

1
2
3
4
5
6
7
message = ""
while True:
message = input("please input something:")
if message == 'quit':
break
else:
print(f"your input the message is :{message}")

输出结果为:

1
2
3
4
5
6
7
8
9
10
please input something:hello 
your input the message is :hello

please input something:python
your input the message is :python

please input something:world
your input the message is :world

please input something:quit

7.2.5 在循环中使用continue

要返回循环开头,并根据条件测试结果决定是否继续执行循环,可使用continue语句,它不像break语句那样不再执行余下的代码并退出整个循环。

1
2
3
4
5
6
cur_number = 0
while cur_number < 10:
cur_number += 1
if(cur_number % 2 == 0):
continue
print(cur_number)

输出结果为:

1
2
3
4
5
1
3
5
7
9

7.2.6 避免无限循环

如果程序陷入无限循环,可按Ctrl+C,也可关闭显示程序输出的终端窗口

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

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

7.3.1 在列表之间移动元素

1
2
3
4
5
6
7
8
9
10
unconfirmed_users = ['alice', 'brian', 'candace']
confirmed_users = []
print(unconfirmed_users)
print(confirmed_users)
while unconfirmed_users:
cur_user = unconfirmed_users.pop()
print(f"verifying user:{cur_user.title()}")
confirmed_users.append(cur_user)
print(unconfirmed_users)
print(confirmed_users)

输出结果为:

1
2
3
4
5
6
7
['alice', 'brian', 'candace']
[]
verifying user:Candace
verifying user:Brian
verifying user:Alice
[]
['candace', 'brian', 'alice']

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

1
2
3
4
5
pets = ['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']
print(pets)
while 'cat' in pets:
pets.remove('cat')
print(pets)

输出结果为:

1
2
['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']
['dog', 'dog', 'goldfish', 'rabbit']

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

可使用while循环提示用户输入任意多的信息。

1
2
3
4
5
6
7
8
9
10
11
12
13
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(f"{name} would like to climb {response}")

输出结果为:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
What is your name?zhangsan

which mountain would you like to climb someday?Deanli

would you like to let another person respond?(yes/no)yes


What is your name?lisi

which mountain would you like to climb someday?Devil`s Thumb

would you like to let another person respond?(yes/no)no

---poll results---
zhangsan would like to climb Deanli
lisi would like to climb Devil`s Thumb
Powered By Valine
v1.5.2