Python学习笔记
参考书目:《Python编程从入门到实践(第2版)》,[美] Eric Matthes,袁国忠译
七、用户输入和while循环
1、函数input( )
input( )让程序暂停运行,等待用户输入文本。获取用户输入后,python将其赋给一个变量。
input( )将用户的输入视为字符串,int()可以将数的字符串表示转换成数值表示。
1)向用户提供提示(prompt)
name = input("Please enter your name: ") # 用户输入并按回车键后,输入被赋给变量name
print(f"\nHello,{name}!")
Please enter your name: skye
Hello,skye!
# 当提示超过一行,将提示赋给一个变量
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(f"\nHello,{name}!")
If you tell us who you are, we can personalize the messages you see.
What is your first name? skye
Hello,skye!
2)使用int( )获取数值输入
age = input("How old are you: ")
age = int(age)
age >= 18
How old are you: 23
True
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
hello
Tell me something, and I will repeat it back to you:
Enter ‘quit’ to end the program. quit
2)使用标志(flag)
用标志的True or False代替变量的判断
active = True
while active:
message = input(prompt)
if message == 'quit' :
active = False
else:
print(message)
Tell me something, and I will repeat it back to you:
Enter ‘quit’ to end the program. hello
hello
Tell me something, and I will repeat it back to you:
Enter ‘quit’ to end the program. quit
3)使用break退出循环
while True:
message = input(prompt)
if message == 'quit':
break
else:
print(message)
Tell me something, and I will repeat it back to you:
Enter ‘quit’ to end the program. hello
hello
Tell me something, and I will repeat it back to you:
Enter ‘quit’ to end the program. 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
3、用while循环处理列表和字典
for循环也可以遍历列表,但不能修改。
1)在列表间移动元素
unconfirmed = ['dog','cat','fish','rabbit','cat'] # 待验证列表
confirmed = [] # 储存已验证的空列表
while unconfirmed:
current = unconfirmed.pop()
confirmed.append(current)
print("The following have been confirmed: ")
for confirmed_one in confirmed:
print(confirmed_one)
The following have been confirmed:
cat
rabbit
fish
cat
dog
2)删除列表元素
pets = ['dog','cat','fish','rabbit','cat']
print(pets)
while 'cat' in pets:
pets.remove('cat')
print(pets)
[‘dog’, ‘cat’, ‘fish’, ‘rabbit’, ‘cat’]
[‘dog’, ‘fish’, ‘rabbit’]