第七章:用户输入和while循环
文章目录
7.1 函数input()的工作原理
- 函数input()让程序暂停运行,等待用户输入一些文本。获取用户输入后,Python将其赋值给一个变量,以方便调用。
任务: 让用户输入文本,把文本呈现给用户
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.Hello python world!
Hello python world!
7.1.1 编写清晰的程序
- 使用input()时,应指定清晰易懂的提示,准确地指出希望用户提供什么样的信息
- 在提示末尾(冒号后面)包含一个空格,将提示与用户输入分开
name = input("Please enter your name: ")
print(f"\nHello, {name}!")
Please enter your name: Tiya
Hello, Tiya!
#提示超过一行,可将提示赋给一个变量
prompt = "If you tell us who you are, we can personlize the message you see."
prompt += "\nWhat is your first name? " # +=的目的在前面字符串末尾附加一个字符串
name = input(prompt)
print(f"\nHello, {name}!")
If you tell us who you are, we can personlize the message you see.
What is your first name? Tiya
Hello, Tiya!
7.1.2 使用int()获取数值输入
- input()将用户输入解读为字符串
age = input("How old are you? ")
How old are you? 21
age >= 18
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-10-4ce6028355cc> in <module>
----> 1 age >= 18
TypeError: '>=' not supported between instances of 'str' and 'int'
- 解决办法:使用int()将字符串转化为数值表示
age = int(age)
age >=18
True
heigt = input("How tall are you, in inches? ")
heigt = int(heigt)
if heigt >= 48:
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!
7.1.3 求模运算符
- 求模运算符(%):将两个数相除并返回余数
任务: 判断一个数是奇数还是偶数
number = input("Enter a number, and I'll tell you if it's even or odd: " )
number = int(number)
if number % 2 == 0:
print(f"\nThe number {number} is even.")
else:
print(f"\nThe number {number} is odd.")
Enter a number, and I'll tell you if it's even or odd: 24729834
The number 24729834 is even.
7.2 while 循环
- for 循环:针对集合中每一个元素都执行一个代码块
- while循环:不断运行,直到指定的条件不满足
7.2.1 使用while循环
任务: 打印1-5
current_number = 1
while current_number <= 5:
print(current_number)
current_number += 1
1
2
3
4
5
7.2.2 让用户选择何时退出
任务: 定义一个退出值, 只要用户不输入这个值,程序将继续运行
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.hhh
hhh
Tell me something,and I will repeat it back to you:
Enter 'quit' to end the program.quit
quit
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': #仅在消息不是quit时打印
print(message)
Tell me something,and I will repeat it back to you:
Enter 'quit' to end the program.fsdfsd
fsdfsd
Tell me something,and I will repeat it back to you:
Enter 'quit' to end the program.quit
7.2.3 使用标志
- 多个不同的事件导致程序停止运行退出
- 定义一个变量(标志,flag),用于判断整个程序是否处于活动状态
- 程序在标志为True时继续,在任何事件导致标志值为False时程序停止
- while语句中只需检查一个条件:标志的当前值是否为True,然后将其他测试都放在其他地方
- 在复杂程序中,标志很有用——在任意时间导致活动标志变成False时,主游戏循环将退出,此时可以显示一条游戏结束信息,并让用户选择是否要重玩
prompt = "\nTell me something,and I will repeat it back to you: "
prompt += "\nEnter 'quit' to end the program."
active = True
while active:
message = input(prompt)
if message == 'quit': #仅在消息不是quit时打印
active = False
else:
print(message)
Tell me something,and I will repeat it back to you:
Enter 'quit' to end the program.quit
7.2.4 使用break退出循环
- break——立即退出while循环,不再运行循环中剩余的代码,也不管条件测试的结果
- 在任何循环中都可以使用break语句
prompt = "\nPlease enter the name of a city you have visited: "
prompt += "\nEnter 'quit' when you finished."
while True:
city = input(prompt)
if city == 'quit': #仅在消息不是quit时打印
break
else:
print(f"I'd love to go to {city.title()}.")
Please enter the name of a city you have visited:
Enter 'quit' when you finished.sdflk
I'd love to go to Sdflk.
Please enter the name of a city you have visited:
Enter 'quit' when you finished.s
I'd love to go to S.
Please enter the name of a city you have visited:
Enter 'quit' when you finished.df
I'd love to go to Df.
Please enter the name of a city you have visited:
Enter 'quit' when you finished.quit
7.2.5 在循环中使用continue
- break——立即退出while循环,不再运行循环中剩余的代码,也不管条件测试的结果
- continue——返回循环开头,并根据条件测试的结果决定是否继续执行循环
任务: 只打印1-10中的奇数
current_number = 0
while current_number < 10:
current_number += 1
if current_number % 2 == 0:
continue
print(current_number)
1
3
5
7
9
7.2.6 避免无限循环
- 每个while循环都必须有停止运行的途径
x = 1
while x <= 5:
print(x)
x += 1
1
2
3
4
5
# 无限循环,不要尝试,可按ctrl+C终止程序
#x = 1
#while x <= 5:
# print(x)
7.3 使用while循环处理列表和字典
- for循环可有效的遍历列表,但不适合修改列表,会导致Python难以跟踪其中的元素
- 要在遍历列表的同时对其元素修改,可以使用while循环
7.3.1 在列表之间移动元素
任务: 假设一个列表包含新注册但还未验证的用户,验证这些用户后,如何将其移到另一个已验证用户列表中
- 使用while循环,在验证用户的同时将其从未验证用户列表中提取出来,再将其加入另一个已验证用户列表中
unconfirmed_users = ['alice', 'brian', 'candace']
confirmed_users = []
#验证每个用户,直到没有未验证用户为止,将每个验证用户移到已验证用户列表中
while unconfirmed_users:
current_user = unconfirmed_users.pop()
print(f"Verifying user: {current_user.title()}")
confirmed_users.append(current_user)
#显示所有已验证用户
print(f"\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
7.3.2 删除为特定值的所有列表元素
- remove()一次只能删除一个特定值
- 在while 循环使用remove(),直到列表中不再包含特定元素
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.3.3 使用用户输入来填充字典
任务: 创建一个调查程序,其中循环每次执行时都提示输入被调查者的名字的回答,将收集的数据存储在一个字典中,以便将回答同被调查者关联起来
#设置一个空字典
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}.")
What is your name? sdf
Which mountain would you like to climb someday?fsdfsg
Would you like to let another person respond? (yes/no)yes
---Poll Results---
sdf would like to climb fsdfsg.
What is your name? jh
Which mountain would you like to climb someday?fhg
Would you like to let another person respond? (yes/no)no
---Poll Results---
sdf would like to climb fsdfsg.
jh would like to climb fhg.