Python学习之路(7)用户输入和while循环

茴香豆 Lv5

在本章中,你将学习如何接收用户输入,让程序能够对其进行处理。你还将学习如何让程序不断地运行,直到指定的条件不满足为止。

1.函数input()

input()让程序暂停运行,等待用户输入一些文本,再将这些文本呈现给用户。

1
2
3
4
5
6
# input 函数
message = input("Tell me something, and I will repeat it back to you: ")
print(message)
# output:
# Tell me something, and I will repeat it back to you: Hello!
# Hello!

函数input()接受一个参数:即要向用户显示的提示或说明,让用户知道该怎么做。

2.while循环

2.1使用while循环

1
2
3
4
5
6
7
8
9
10
11
# while
current_number = 1
while current_number <= 5:
print(current_number)
current_number += 1
# output:
# 1
# 2
# 3
# 4
# 5

2.2让用户选择何时退出

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# select when to exit
prompt = "Tell me something, and I will repeat it back to you:"
prompt += "\nEnter 'quit' to end the program. input:"
message = ""
while message != 'quit':
message = input(prompt)
if message != 'quit':
print(message)
# output
Tell me something, and I will repeat it back to you:
Enter 'quit' to end the program. input:Hello
Hello
Tell me something, and I will repeat it back to you:
Enter 'quit' to end the program. input:Hello again
Hello again
Tell me something, and I will repeat it back to you:
Enter 'quit' to end the program. input:quit

2.3使用break退出循环

1
2
3
4
5
6
7
8
9
10
11
12
13
14
prompt = "Tell me something, and I will repeat it back to you:"
prompt += "\nEnter 'quit' to end the program. input:"
while True:
city = input(prompt)
if city == 'quit':
break
else:
print(city.title())
#output
Tell me something, and I will repeat it back to you:
Enter 'quit' to end the program. input:Hello
Hello
Tell me something, and I will repeat it back to you:
Enter 'quit' to end the program. input:quit

2.4在循环中使用continue

continue,跳过后面的语句直接执行下一次循环。

3.使用while处理字典列表

3.1在列表之间移动元素

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

1
2
3
4
5
6
7
8
9
10
11
12
# use 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)
#output:
Verifying user: Candace
Verifying user: Brian
Verifying user: Alice

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

使用while删除列表中所有 ‘cat’ 元素。

1
2
3
4
5
pets = ['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']
print(pets) # ['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']
while 'cat' in pets:
pets.remove('cat')
print(pets) # ['dog', 'dog', 'goldfish', 'rabbit']
  • Title: Python学习之路(7)用户输入和while循环
  • Author: 茴香豆
  • Created at : 2022-07-01 21:58:51
  • Updated at : 2022-07-01 23:30:45
  • Link: https://hxiangdou.github.io/2022/07/01/Python_7/
  • License: This work is licensed under CC BY-NC-SA 4.0.
Comments