【Python】07 用户输入和while循环

前言:函数input(),使用while循环让程序不断地运行,编写交互式程序

7.1 函数input()

接受一个参数,即要向用户显示的提示或者说明。

编写清晰度程序,提示清晰且易于理解

prompt = 'if you tell us who you are, we can personalize the messages you see.'
prompt +='\nwhat is your name?' #用+=号处理超过一行的提示

7.1.2 使用int()来获取数值输入

#rollercoaster.py
height = input('how tall are you, in inches?')
height = int(height)

if height >=36:
    print("\nyou're tall enough to ride!")
else:
    print("\nyou'll be able to ride when you're a little older.")

7.1.3 求模运算符 %:两个数相除并返回余数

4%3
#返回1

Tips:可以用求模数判断数字是奇数还是偶数,返回0即为偶数

7.2 while循环

for循环是针对集合中的每个元素的一个代码块,while循环则不断进行,知道指定的条件不满足为止。

7.2.2 让用户选择何时退出

prompt = 'if you tell us who you are, we can personalize the messages you see.'
prompt += "\nenter 'quit' to end the program." #用+=号处理超过一行的提示
message = ''
while message != 'quit':
      message = input(prompt)
       
      if message != 'quit':
      print(message)

7.2.3 使用标志

让程序在标志为True的时候继续运行,为False的时候停止运行。

prompt = 'if you tell us who you are, we can personalize the messages you see.'
prompt += "\nenter 'quit' to end the program." #用+=号处理超过一行的提示

active = True
while active:#可以给标志指定任何名称
    message = input(prompt)
    
    if message == 'quit':
        active = False
    else:
        print(message)

7.2.4 使用break退出循环

break语句用于控制程序流程,立即退出while循环,不再运行循环中余下的代码。

prompt = '\nplease enter the name of a city you have visited:'
prompt += "\nenter 'quit' when you are finished."
while True:
    city = input(prompt)
    
    if city == "quit":
        break
    else:
        print("i'd love to go to "+ city.title()+'!')

输出结果:


输出.png

7.2.5 在循环中使用continue

返回循环开头,并根据条件测试结果决定是否继续执行循环。

current_number = 0
while current_number < 10:
    current_number +=1
    if current_number % 2 == 0:
        continue
        
    print(current_number)

输出结果:


输出2.png

7.2.6 避免无限循环

如果程序陷入无限循环,可以command+C,也可关闭显示程序输出的终端窗口。
确认程序至少有一个地方可以让循环条件为False或者让break语句得以执行。

7.3 用while循环来处理列表和字典

在for循环中不应修改列表,会导致难以跟踪其中的元素。通过将while循环同列表和字典结合起来,可收集、存储并组织大量输入,供查看和显示。

7.3.1 在列表之间移动数据

#首先创建一个待验证用户列表和一个已验证用户列表
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)
    
#显示所有已验证用户
print("\nthe following users have been confirmed:")
for confirmed_user in confirmed_users:
    print(confirmed_user.title())

输出结果:


输出3.png

7.3.2 删除包含特定值的所有列表元素

单独使用remove()可以删除第一个值;删除所有值,需要使用while循环

pets = ['dog','cat','dog','goldfish','cat','rabbit','cat']
while 'cat' in pets:
    pets.remove('cat')
print(pets)

输出:['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 (name + " would like to climb " + response + '.')

输出结果:


输出4.png

你可能感兴趣的:(【Python】07 用户输入和while循环)