用户输入和while循环
1. input()
(1) 工作原理
让程序暂停运行,等待用户输入,在用户按回车键后将用户输入存储在变量中并继续运行
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 + "!")
(2) int() 获取数值输入
input() 将用户输入解读为字符串,int() 可将输入视为数值
- 注意:并非真的转换
- 将数值输入用于计算和比较前,务必将其转换为数值表示
>>> age = input("How old are you?")
How old are you? 21
>>> age
'21'
>>> age = int(age)
>>> age >= 18
True
(3) 求模运算符 %
>>> 4 % 3
1
>>> 5 % 3
2
>>> 6 % 3
0
>>> 7 % 3
1
(4) Python 2.7 中获取输入
raw_input()
- Python 2.7的 input() 将用户输入解读为Python代码并运行
2. while循环
(1) 让用户选择何时退出
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
(2) 使用标志
prompt = "\nTell me something, and I will repeat it back to you:"
prompt += "\nEnter 'quit' to end the program."
active = True
# 简化了while语句,因为不需要在其中做任何比较
while active:
message = input(prompt)
if message == 'quit':
active = False
else:
print(message)
(3) break
可退出任何循环,包括while和for
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() + "!")
=>
Please enter the name of a city you have visited:
Enter 'quit' when you are finished. New York
I'd love to go to New York!
Please enter the name of a city you have visited:
Enter 'quit' when you are finished. San Francisco
I'd love to go to San Francisco!
Please enter the name of a city you have visited:
Enter 'quit' when you are finished. quit
(4) continue
返回到循环开头,并根据条件测试结果决定是否继续执行循环
current_number = 0
while current_number < 10:
current_number += 1
if current_number % 2 == 0
continue
print(current_number)
=>
1
3
5
7
9
(5) 退出无限循环
有以下两种方式
- Ctrl + C
- 关闭显示程序输出的终端窗口
(6) 处理列表
在for循环中不应修改列表,否则将导致Python难以跟踪其中的元素,要在遍历的同时修改,可使用while
1) 在列表之间移动元素
unconfirmed_users = ['alice', 'brian', 'candace']
confirmed_users = []
# "while 列表名":列表不为空返回True,否则返回False
while unconfirmed_users:
current_user = unconfirmed_users.pop()
print("Verifying user: " + current_user.title())
unconfirmed_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) 删除列表中所有特定值元素
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']
(7) 使用用户输入来填充字典
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? 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 Results ---
Lynn would like to climb Devil's Thumb.
Eric would like to climb Denali.