input 输入原理(含 while 循环,由用户终止程序的代码的方法)
prompt = "please tell me something ,I will repeat it "
prompt += " unless you put ' exit' "
message =""
while message != 'exit':
message = input(prompt)
print(message)
以上程序的不足点就是,当输入exit时,该信息也将会被打印
优化:
在终止时,不再打印用户输入的exit,并且可以忽略用户输入的大小写(可以用于制作验证码)
active = True
prompt_p = "please tell me something ,I will repeat it "
prompt_p += " unless you put ' exit' "
message_2 =""
while message_2.lower() != 'exit':
message_2 = input(prompt_p)
if message_2.lower() == 'exit':
active = False
else:
print(message_2)
使用break退出循环
tips = 'Enter a city you have visited '
tips += 'if you have finished , please enter "quit" !'
while True : #这个玩意打头的程序将一直不停地循环,直到遇见break语句
city = input(tips)
if city.lower() == 'quit':
break
else:
print(f"I'd love to go to {city.title()} !")
在循环中使用countinue
#打印1——10的奇数
num = 0
while num < 10:
num +=1
if num % 2==0:
continue #当遇见if语句的条件成立时,跳过该次循环,继续下一次,不像break一样退出
print(num)
使用循环时要注意避免无限循环
当出现无限循环时:使用以下方法,最好还是Ctrl+c
Ctrl+c是强制中断程序的执行,杀死程序的进程;
Ctrl+z是将任务中断,挂起的状态,进程还存在,任务还没有结束;
使用 while循环处理 列表和字典
for循环难以跟踪在循环中存在变化的状况
模拟用户验证过程(在列表之间移动元素)
unconfirmed_users = ['ty','sh','tr']
confirmed_users =[]
while unconfirmed_users:
current_user=unconfirmed_users.pop() #不断弹出最后一个元素,直到列表为空
print(f"verifying user : {current_user.title()}")
confirmed_users.append(current_user)
print("\nThe users have been confirmed :")
for confirmed_user in confirmed_users:
print(confirmed_user.title(),end=" ")
使用while循环删除列表中的特定的所有元素
pets = ['dog','cat','dog','goldfish','rabbit','dog','cx']
print(pets)
while 'dog' in pets: #当存在dog时,会一直执行循环
pets.remove('dog')
print(pets)
使用用户输入来填充字典 (可以做问卷小程序)
responses={} #创建一个空的字典
polling_active =True #设置一个标志,用于检查程序是否继续
while polling_active :
name=input("\n What is your name ?")
response = input("Which mointain would you like to climb someday?")
responses[name] =response #将名字与答案储存到字典中
repeat = input('would you like to let another person respond ? (yes/no)')
if repeat.lower() =='no':
polling_active =False
print('---POLL RESULTS---')
for name ,response in responses.items():
print(f"{name}would like to climb {response}")