Python基础(七)
用户输入和while循环
1 函数input()的工作原理
函数input()让程序暂停运行,等待用户输入一些文本。
获取用户输入后,Python将其赋给一个变量。
message = input("Tell me something, ang I will repeat it back to you: ")
print(message)
以上代码中,用户输入的文本会赋给变量message,如果打印message变量会发生什么呢?
Tell me something, ang I will repeat it back to you: Hello everyone
Hello everyone
首先是一句提示语句,接下来的便是用户输入的文本。
1.1 编写清晰的程序
name = input("Please enter your name: ")
print(f"\nHello,{name}")
打印结果:
Please enter your name: Mary
Hello,Mary
和我们学习的第一个input()程序十分相似。
1.2 使用int()来获取数值输入
使用函数input()时,Python将用户输入解读为字符串。
首先来看一个例子:
age = input("How old are you? ")
print(age)
print(age >= 18)
打印结果:
Traceback (most recent call last):
File "D:\Python\pythonProject\myFirstPython.py", line 334, in <module>
print(age >= 18)
TypeError: '>=' not supported between instances of 'str' and 'int'
说明输入结果用于数值比较时,Python会发生错误。
为解决这个问题,可使用函数int()
age = input("How old are you? ")
age = int(age)
print(age >= 18)
用户根据提示输入19后,Python将这个数解读为字符串,随后int()将这个字符串转换成了数值表示。
打印结果如下:
How old are you? 19
True
如何在实际程序中使用函数int()呢?
height = input("How tall are you ,in inches?")
height = int(height)
if height >= 48:
print("\nYou 're tall enough to ride!")
else:
print("\nYou 'll be able to ride when you 're a little older.")
用户输入49,打印结果如下:
How tall are you ,in inches?49
You 're tall enough to ride!
将数值输入用于计算和比较前,务必将其转换为数值表示。
1.3 求模运算符
求模运算符(%)是个很有用的工具,它将两个数相除并返回余数:
num = 4%3
print(num)
打印结果:
1
2 while 循环简介
2.1 使用while循环
current_number = 1
while current_number <= 5:
print(current_number)
current_number+=1
第一行,将1赋给变量current_number,从而指定从1开始数。
while循环设置的条件为current_number 变量小于等于5,所以只要变量满足条件就会一直执行while循环里的语句。
打印结果:
1
2
3
4
5
2.2 让用户选择何时退出
如果用户想让while循环一直执行,直到用户不想让它执行为止,那么我们可以设置一个退出值:
prompt = "\nTell me something,and I will repeat it back to you: "
message = ""
while message != 'quit':
message = input(prompt)
print(message)
直到用户输入‘quit’,while循环才会停止运行。
Tell me something,and I will repeat it back to you: z
z
Tell me something,and I will repeat it back to you: quit
quit
2.3 使用标志
prompt = "\nTell me something,and I will repeat it back to you: "
active = True
while active:
message = input(prompt)
if message == 'quit':
active = False
else:
print(message)
定义一个变量active,用于while的条件判断,初始值为True,如果用户输入为:‘quit’,则将active变量改为False,退出while循环。
打印结果如下:
Tell me something,and I will repeat it back to you: Hello
Hello
Tell me something,and I will repeat it back to you: Hi
Hi
Tell me something,and I will repeat it back to you: exit
exit
Tell me something,and I will repeat it back to you: quit
3 使用while循环处理列表和字典
3.1 在列表之间移动元素
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("\nThe following users have been confirmed: ")
for confirmed_user in confirmed_users:
print(confirmed_user.title())
先创建了一个未验证用户列表,然后创建了一个空列表。
while循环不断运行,直至第一个列表为空。循环中,用pop()方法从第一个列表中末尾删除一个元素。
将删除元素赋给一个变量,然后将变量添加到开始创建的空列表中。
结果如下:
Verifying user: Candace
Verifying user: Brian
Verifying user: Alice
The following users have been confirmed:
Candace
Brian
Alice
3.2 删除为特定值的所有列表元素
pets = ['dog','cat','dog','goldfish','cat','rabbit','cat']
print(pets)
while 'cat' in pets:
pets.remove('cat')
print(pets)
利用while循环,直至列表中没有’cat’元素。每次删除一个‘cat’元素。
打印结果:
['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']
['dog', 'dog', 'goldfish', 'rabbit']