用户输入和while 循环
本篇章,主要讲解input输入函数,和while循环的多种控制方式,比如设置活动标志、使用break语句以及使用continue等,还讲解while循环在列表之间移动元素以及如何从列表中删除包含的指定值的元素,还会讲解while循环和字典的结合。
input函数
只强调一点,input()函数输出的是一个字符串,如果获取用户输入是数字,其实是数字的字符串形式,还是字符串,如果要变为数字,使用int(input(29)),这样就OK了,其他不多说。
while循环
- 控制方式1:设置活动变量
current_number = 1
while current_number<=5:
print(current_number)
current_number += 1
- 控制方式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)
if message != 'quit':
print(message)
- 控制方式3:使用标志
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':
active = False
else:
print(message)
写到这里,我感觉这while三种控制方式,都一样,都是提前设定一个变量,然后while循环体内根据需要改变这个变量取值,当这个变量不满足while的循环条件时,就会跳出循环。
- 控制方式4:使用break退出循环
prompt = "\nPlease enter the name of a city you have visited:"
prompt += "\nEnter 'quit' to end the program. "
while True:
city = input (prompt)
if city == 'quit':
break
else:
print("I'd love to go to " + city.title() + "!"
- 控制方式5:使用continue
current_number = 0
while current_number < 10:
current_number += 1
if current_number % 2 == 0:
continue
print(current_number)
while 循环处理列表和字典
for 循环是一种遍历列表的有效方式,但是for循环中不应修改列表,否则将导致python难以跟踪其中的元素。要想遍历列表的同时对其进行修改,可使用while循环。通过将while循环同列 表和字典结合起来使用,可收集、存储并组织大量输入,供以后查看和显示。
- 列表之间移动元素
# 对待定未验证的用户进行验证,类似下面代码
unconfirmed_users = ['alice', 'brian', 'candace']
confirmed_users = []
while unconfirmed_users:
current_user = unconfirmed_users.pop()
print("Verifying user: " + current_user.title())
confirmed_users.append(current_user)
- 删除包含指定值的所有列表
pets = ['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']
while 'cat' in pets:
pets.remove('cat')
- 使用用户输入填充字典
responses = {}
polling_active = True
while polling_active:
name = input('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
目前为止,复习了python的部分基础知识点,虽然以前看过也很简单,但却仍有所获。这周争取早点结束python基础知识的学习,希望看过一遍后,能够对python有个系统的掌握,加油!
网友评论