函数input()让程序暂停运行,等待用户输入一些文本。获取用户输入后,Python将其存储在一个变量中

1
2
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: 你好
你好
1
2
3
4
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? KJ

Hello, KJ!

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

input()把输入的文本转换成字符串
int()可以把字符串转换成整型

1
2
3
4
5
6
7
# 使用int()将input()的字符串转成整型
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!

求模运算符%是一个很有用的工具,它将两个数相除并返回余数

1
2
3
4
5
6
7
# 用于判断奇偶数
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: 12341241451

The number 12341241451 is odd.

while循环


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

选择何时退出

1
2
3
4
5
6
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)
Tell me something, and I will repeat it back to you:
Enter 'quit' to end the program. 画面上,天空是铁青色混合着火焰的颜色,唯一的一株巨树矗立着,已经枯死的树枝向着四面八方延伸,织成一张密网,支撑住皲裂(jūnliè)的天空。
画面上,天空是铁青色混合着火焰的颜色,唯一的一株巨树矗立着,已经枯死的树枝向着四面八方延伸,织成一张密网,支撑住皲裂(jūnliè)的天空。

Tell me something, and I will repeat it back to you:
Enter 'quit' to end the program. 荒原上枯骨满地,黑色的巨兽正从骨骸堆的深处腾起,双翼挂满骷髅,张开巨大的膜翼后,仰天吐出黑色的火焰。
荒原上枯骨满地,黑色的巨兽正从骨骸堆的深处腾起,双翼挂满骷髅,张开巨大的膜翼后,仰天吐出黑色的火焰。

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

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

1
2
3
4
5
6
7
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. 我不再迷茫 思念是唯一的行囊
我不再迷茫 思念是唯一的行囊

Tell me something, and I will repeat it back to you:
Enter 'quit' to end the program. 漫天的星光 有一颗是你的愿望
漫天的星光 有一颗是你的愿望

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

使用标志

可定义一个变量,用于判断整个程序是否处于活动状态。这个变量被称为标志

1
2
3
4
5
6
7
8
9
10
11
12
# 把这个标志命名为active(可给它指定任何名称)
prompt = "\n我会重复你的话: "
prompt += "\n输入‘quit’退出 "

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

if message == 'quit':
active = False
else:
print(message)
我会重复你的话:
输入‘quit’退出爆裂鼓手
爆裂鼓手

我会重复你的话:
输入‘quit’退出黑天鹅
黑天鹅

我会重复你的话:
输入‘quit’退出小丑
小丑

我会重复你的话:
输入‘quit’退出quit

备注
在while循环中,我们在用户输入后使用一条if语句来检查变量message的值。如果用户输入的是’quit’,我们就将变量active设置为False,这将导致while循环不再继续执行

使用 break 退出循环

break语句用于控制程序流程,可使用它来控制哪些代码行将执行

1
2
3
4
5
6
7
8
9
10
prompt = "\n请输入你喜欢的城市: " 
prompt += "\n输入‘quit’退出 "
messages = []
while True:
message = input(prompt)
if message == 'quit':
break
else:
messages.append(message)
print(messages)
请输入你喜欢的城市: 
输入‘quit’退出  北京

['北京']

请输入你喜欢的城市: 
输入‘quit’退出  东京

['北京', '东京']

请输入你喜欢的城市: 
输入‘quit’退出  首尔

['北京', '东京', '首尔']

请输入你喜欢的城市: 
输入‘quit’退出  quit

使用 continue继续循环

continue继续循环,也就是回到循环的开头

1
2
3
4
5
6
7
current_number = 0 
while current_number < 10:
current_number += 1
if current_number % 2 == 0:
continue

print(current_number)
1
3
5
7
9

备注
如果整除结果为0(意味着current_number可被2整除),就执行continue语句,
让Python忽略余下的代码,并返回到循环的开头。如果当前的数字不能被2整除,就执行循环中
余下的代码,Python将这个数字打印出来

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

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

1
2
3
4
5
6
7
8
9
10
11
unconfirmed_users = ['A', 'B', 'C'] 
confirmed_users = []
while unconfirmed_users:
current_user = unconfirmed_users.pop()

print("Verifying user: " + current_user.title())
confirmed_users.append(current_user)

print("\n显示所有已验证的用户:")
for confirmed_user in confirmed_users:
print(confirmed_user.title())
Verifying user: C
Verifying user: B
Verifying user: A

显示所有已验证的用户:
C
B
A

while循环将不断地运行,直到列表unconfirmed_users变成空的

删除包含特定值的所有列表元素

1
2
3
4
5
6
7
8
9
10
11
12
13
# 删除所有特定值元素
pets = ['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']
print(pets)

# 进入这个循环后,Python删除第一个'cat'并返回到while代码行,然后发现'cat'还包含在列表中,因此再次进入循环
while 'cat' in pets:
pets.remove('cat')

# 进入这个循环后,Python删除第一个'dog'并返回到while代码行,然后发现'dog'还包含在列表中,因此再次进入循环
while 'dog' in pets:
pets.remove('dog')

print(pets)
['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']
['goldfish', 'rabbit']

使用用户输入来填充字典

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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 + ".")
What is your name?  A
Which mountain would you like to climb someday?  黄山
Would you like to let another person respond? (yes/ no)  yes

What is your name?  B
Which mountain would you like to climb someday?  白云山
Would you like to let another person respond? (yes/ no)  yes

What is your name?  C
Which mountain would you like to climb someday?  岳麓山
Would you like to let another person respond? (yes/ no)  no

--- Poll Results ---
A would like to climb 黄山.
B would like to climb 白云山.
C would like to climb 岳麓山.