为了账号安全,请及时绑定邮箱和手机立即绑定

Python基础之While循环

标签:
Python

一、摘要

本片博文将介绍input()函数和while循环的使用

二、input()函数

函数input() 让程序暂停运行,等待用户输入一些文本。获取用户输入后,Python将其存储在一个变量中,以方便你使用。

message = input("Tell me something, and I will repeat it back to you: ")print(message)

函数input() 接受一个参数:即要向用户显示的提示 或说明,让用户知道该如何做。在这个示例中,Python运行第1行代码时,用户将看到提示Tell me something, and I will repeat it back to you: 程序等待用户输入,并在用户按回车键后继续运行。输入存储在变量message 中,接下来的print(message) 将输入呈现给用户,有时候,提示可能超过一行,例如,你可能需要指出获取特定输入的原因。在这种情况下,可将提示存储在一个变量中,再将该变量传递给函数input() 。这样,即便提示超过一行,input() 语句也非常清晰。

prompt = "If you tell us who you are, we can personalize the messages you see."prompt += "\nWhat is your first name? "name = input(prompt)print("\nHello, " + name + "!")

使用函数input() 时,Python将用户输入解读为字符串。请看下面让用户输入其年龄的解释器会话:

>>> age = input("How old are you? ")
How old are you? 21>>> age'21'

用户输入的是数字21,但我们请求Python提供变量age 的值时,它返回的是'21' ——用户输入的数值的字符串表示,是个字符串自然就不能当作数字来使用,否则会报TypeError,我们如果要当作数字来使用,就需要使用int()函数来转换

>>> age = input("How old are you? ")
How old are you? 21>>> age = int(age)>>> age >= 18True
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.")
number = input("Enter a number, and I'll tell you if it's even or odd: ")
number = int(number)if number % 2 == 0:
  print("\nThe number " + str(number) + " is even.")else:
  print("\nThe number " + str(number) + " is odd.")

三、while循环

while 循环不断地运行,直到指定的条件不满足为止

current_number = 1while current_number <= 5:
  print(current_number)
  current_number += 1

只要current_number 小于或等于5,就接着运行这个循环。循环中的代码打印current_number 的值,再使用代码current_number += 1 (代码current_number = current_number + 1 的简写)将其值加1。只要满足条件current_number <= 5 ,Python就接着运行这个循环。由于1小于5,因此Python打印1 ,并将current_number 加1,使其为2 ;由于2小于5,因此Python打印2 ,并将current_number 加1 ,使其为3 ,以此类推。一旦current_number 大于5,循环将停止,整个程序也将到此结束

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)
  print(message)

可使用while 循环让程序在用户愿意时不断地运行,我们在其中定义了一个退出值,只要用户输入的不是这个值,程序就接着运行

复制代码

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)

复制代码

在要求很多条件都满足才继续运行的程序中,可定义一个变量,用于判断整个程序是否处于活动状态。这个变量被称为标志 ,充当了程序的交通信号灯。你可让程序在标志为True 时继续运行,并在任何事件导致标志的值为False 时让程序停止运行。这样,在while 语句中就只需检查一个条件——标志的当前值是否为True ,并将所有测试(是否发生了应将标志设置为False 的事件)都放在其他地方,从而让程序变得更为整洁。

复制代码

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 循环,不再运行循环中余下的代码,也不管条件测试的结果如何,可使用break 语句。break 语句用于控制程序流程,可使用它来控制哪些代码行将执行,哪些代码行不执行,从而让程序按你的要求执行你要执行的代码。

复制代码

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

复制代码

注意:在任何Python循环中都可使用break 语句。例如,可使用break 语句来退出遍历列表或字典的for 循环。

要返回到循环开头,并根据条件测试结果决定是否继续执行循环,可使用continue 语句,它不像break 语句那样不再执行余下的代码并退出整个循环。

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

if 语句检查current_number 与2的求模运算结果。如果结果为0(意味着current_number 可被2整除),就执行continue 语句,让Python忽略余下的代码,并返回到循环的开头。如果当前的数字不能被2整除,就执行循环中余下的代码,Python将这个数字打印出来

四、使用while 循环来处理列表和字典

for 循环是一种遍历列表的有效方式,但在for 循环中不应修改列表,否则将导致Python难以跟踪其中的元素。要在遍历列表的同时对其进行修改,可使用while 循环。通过将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)# 显示所有已验证的用户print("\nThe following users have been confirmed:")for confirmed_user in confirmed_users:
  print(confirmed_user.title())

复制代码

  • 删除包含特定值的所有列表元素:我们可以使用函数remove() 来删除列表中的特定值,但每次只能删除一个,如果要删除列表中所有包含特定值的元素,该怎么办呢?假设你有一个宠物列表,其中包含多个值为'cat' 的元素。要删除所有这些元素,可不断运行一个while 循环,直到列表中不再包含值'cat' ,如下所示:

pets = ['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']print(pets)while 'cat' in pets:
  pets.remove('cat')print(pets)
  • 使用用户输入来填充字典:可使用while循环提示用户输入任意数量的信息。下面来创建一个调查程序,其中的循环每次执行时都提示输入被调查者的名字和回答。我们将收集的数据存储在一个字典中,以便将回答同被调查者关联起来:

复制代码

responses = {}# 设置一个标志,指出调查是否继续polling_active = Truewhile 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 + ".")

复制代码

原文出处:https://www.cnblogs.com/davieyang/p/10236646.html  

点击查看更多内容
TA 点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
  • 推荐
  • 评论
  • 收藏
  • 共同学习,写下你的评论
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消