这里写自定义目录标题
提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
文章目录
前言
学习如何接受用户输入,让程序进行处理。还将学习如何让程序不断运行
7.1 函数 input()的工作原理
函数input()让程序暂停运行,等待用户输入一些文本。获取用户输入后,python将其存储在一个变量中
message=input("Tell me something,and i will repeat it bakc to you:")
print(message)
7.1.1 编写清晰的程序
每当你使用函数input()时,都应指定清晰而易于明白的提示
name=input("Please enter your name:")
print(f"Hello,{name}")
7.1.2 使用int()来获取数值输入
使用函数input()时,python将用户输入解读为字符串
age=input("How old are you?")
age
用户输入的是数字21,返回的是’21’,因为这个数字用引号括起了。打印输入没问题,但如果你试图将输入作为数字使用,就会引发错误:
age=input("How old are you?")
age>=18
TypeError: ‘>=’ not supported between instances of ‘str’ and ‘int’
进行数值比较时,python就会引发错误,因为无法将字符串和整数进行比较
age=input("How old are you?")
age=int(age)
age>=18
判断身高要求:
height=input("How tall are you,in inches?")
height=int(height)
if height>=36:
print("\nyou're tall enough to ride!")
else:
print("\nYou're be able to ride when you're a little older.")
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"The number {str(number)} is even")
else:
print(f"The number {str(number)} is odd")
7.2 while循环简介
for循环用于针对集合中的每个元素都一个代码块,而while循环不断地运行,直到条件不满足为止
7.2.1 使用while循环
current_number=1
while current_number <=5:
print(current_number)
current_number+=1
只要current_number小于等于5,就接着运行这个循环。循环中地代码先打印值,然后再加1.
7.2.2 让用户选择合适退出
可使用while循环让程序再用户愿意时不断运行。
prompt="\nTell me something,and i will repeat it back to you:"# 1处
prompt+="\n Enter 'quit' to end the program"
message=""# 创建了一个变量--message,用于存储用户输入地值
while message!='quit':
message=input(prompt)
print(message)
在①处,定义了一条提示信息,告诉用户有两个选择:要么输入一条消息,要么输入退出值quit。
7.2.3 使用标志
在要求很多条件都满足才继续运行地程序中,可定义一个变量,用于判断整个程序是否处于活动状态。这个变量被称为标志,充当程序地交通信号灯。可让程序在标志为True时继续运行,并在任何事件导致标志的值为False时让程序停止运行。这样,在while语句中就只需检查一个条件——标志的当前值是否为true,并将所有测试都放在其他地方,从而让程序变得更为整洁。
prompt="\nTell me something,and i will repeat it back to you:"
prompt+="\n Enter 'quit' to end the program"
active=True# 将变量active设置成了True,简化了while语句
while active:
message=input(prompt)
if message=='quit':
active=False
else:
print(message)
在while循环中,我们在用户输入后使用一条if语句来检查变量message的值。如果输入的是quit,我们将变量active设置为False,这将导致while循环不再继续执行。如果用户输入的不是‘quit’,我们打印消息。
7.2.4 使用break退出循环
break语句可立即退出while循环,不再运行循环中余下的代码。
prompt="\nTell me something,and i will repeat it back to you:"
prompt+="\n Enter 'quit' to end the program"
while True:
city=input(prompt)
if city=='quit':
break
else:
print(f"i'd love to go to {city.title()}")
以while True大头的循环不断运行,直到遇到break语句
注意:在任何python循环中都可使用break语句
7.2.5 在循环中使用continue
要返回循环开头,并根据条件测试结果决定是否继续执行循环,可使用continue语句。
current_number=0
while current_number<10:
current_number+= 1
if current_number % 2==0:
continue
print(current_number)
当能被2整除时,执行continue语句,让python忽略余下的代码,并返回循环的开头。
动手试一试
7.3 使用while循环来处理列表和字典
要在遍历列表的同时对其进行修改,可使用while循环。通过while循环同列表和字典结合起来使用,可收集、存储并组织大量输入,供以后查看和显示
7.3.1在列表之间移动元素
使用while循环,在验证用户的同时将其从未验证用户列表中提取,再将其加入另一个已验证用户列表中
# 首先,创建一个待验证用户列表
# 和一个用于存储已验证用户列表中
unconfirmed_users=['alice','brian','candace']
confirmed_users=[]
# 验证每个用户,直到没有未验证用户为止
# 将每个经过验证的列表都移到已验证用户列表中
while unconfirmed_users:
current_users=unconfirmed_users.pop()#函数pop()以每次一个的方式从列表unconfirmed末尾删除未验证的用户,然后存储到current
print(f"Verifying user:{current_users.title()}")
confirmed_users.append(current_users)
#显示所有已验证的用户
print("\nThe following users have been confirmed:")
for confirmed_user in confirmed_users:
print(confirmed_user.title())
7.3.2 删除包含特定值的所有列表元素
如果要删除列表中所有包含特定值的元素,怎么办?
#pets,py
pets=['dog','cat','goldfish','dog','cat','goldfish']
print(pets)
while 'cat' in pets:
pets.remove('cat')
print(pets)
7.3.3 使用用户输入来填充字典
创建一个一个调查程序,其中的循环每次执行时都提示输入被调查的名字和回答。
# mountain_poll.py
responses={}
#设置一个标志,指出调查是否继续
polling_active=True
while polling_active:
#提示输入被调查者的名字和回答
name=input("\n What 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}")
7.4 小结
- 如何在程序中使用input()来让用户提供信息
- 如何处理文本和数字的输入
- 如何使用while循环让程序按用户的要求不断地运行
- 多种控制while循环流程的方式:设置活动标志
- 使用break,continue语句
- 使用while循环在列表之间移动元素
- 如何从列表中删除所有包含特定值的元素
- 如何结合使用while循环和字典