Python入门基础 第七章:while循环

#7.1 函数input()的工作原理
#函数input()让程序暂停运行,等待用户输入一些文本。获取用户输入后,Python将其赋值给一个变量。
'''例如,下面的程序让用户输入一些文本,再将这些文本呈现给用户:'''
#--------------------------------------------------------

message = input("Tell me something,and I will repeat it back to you:")
print(message)
#--------------------------------------------------------
#函数input()接受一个参数——要向用户显示的提示或说明,让用户知道该如何做。在本例中,用户将看到提示,程序将等待用户输入,并将在用户按回车键后继续运行。
#7.1.1 编写清晰的程序
#每次只用函数input()时,都应指定清晰易懂的提示,准确地指出希望用户提供什么样的信息——指出用户应该输入何种信息的任何提示都行,如下所示:

name = input("Please enter your name: ")
print(f"\nHello,{name}")
#========================================================
#有时候,提示可能超过一行,可以使用'+='在前面赋给变量的字符串末尾附加一个字符串。

prompt = "If you tell us who you are,we can personalize the message you see."
prompt += "\nWhat is your first name?"
name = input(prompt)
print(f"\nHello,{name}")
#7.1.2 使用int()来获取数值输入
#使用函数input()时,Python将用户输入解读为字符串。
'''age = input("How old are you?")
age >= 18'''
# Traceback (most recent call last):
#   File "D:/python_work/training/while循环.py", line 26, in <module>
#     age >= 18
# TypeError: '>=' not supported between instances of 'str' and 'int'
#所有出现错误,以下是解决办法。
age = input("How old are you?")
age = int(age)
age >= 18
#7.1.3 求模运算符
#处理数值信息时,求模运算符(%)是一个很有用的工具,它将两个数相除并返回余数:
''' 4 % 3
1
    5 % 3
2
    6 % 3 
0
    7 % 3
1
'''
#求模运算符不会指出一个数时另一个数的多少倍,只指出余数是多少。
#如果一个数可以被另一个数整除,余数就为0,因此求模运算符将返回0.可以利用这一点来判断一个数是奇数还是偶数:
#--------------------------------------------------

number = input("Enter a number, and I'llq tell you if it's even or odd: ")
number = int(number)
if number % 2 ==0:
    print(f"\nThe number {number} is even.")
else:
    print(f"\nThe number {number} is odd.")
#7.2 while循环简介
#for循环用于针对集合中的每个元素都执行一个代码块,而while循环则不断运行,直到指定的条件不满足为止。
#7.2.1 使用while循环
'''可使用while循环来数数。例如:下面的while循环从1数到5:'''

current_number = 1
while current_number <=5:
    print(current_number)
    current_number += 1   #代码current_number = current_number +1 的简写
#7.2.2 让用户选择何时退出
#我们可以在代码中定义一个退出值,只要用户输入的不是这个值,程序就将接着运行:
#---------------------------------------------------------------

prompt = "\nTell me something, and I eill repeat it back to you :"
prompt += "\nEnter 'quit' to end the program."
message = ""
while message != 'quit':
    message = input(prompt)
    print(message)
#这个程序美中不足的是,它将单词’quit‘也作为一条消息打印了出来。为修复这个问题,只需要使用一个简单的if测试:

prompt = "\nTell me something, and I eill repeat it back to you :"
prompt += "\nEnter 'quit' to end the program."
message = ""
while message != 'quit':
    message = input(prompt)
    if message != 'quit':
        print(message)
#=============================================================
#7.2.3 使用标志
#在前一个示例中,我们让程序在满足指定条件是执行特定的任务。但在更复杂的程序中,很多不同的事件会导致程序停止运行。
#所以我们可以设置一个变量,用于判断整个程序是否处于活动状态。这个变量称为标志(flag),充当程序的交通信号灯。
#可以让程序在标志为True时继续运行,并在任何事件导致标志的值为False时让程序停止运行。
#-------------------------------------------------------------

prompt = "\nTell me something, and I eill 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)
#7.2.4 使用break退出循环
# 要立即退出while循环,不再运行循环中的余下代码,也不管条件测试的结果如何,可使用break语句。break语句用于控制程序流程,可用来控制哪些代码行将执行、
# 哪些代码不执行,从而让程序按你的要求执行你要执行的代码。
'''例如,来看一个让用户指出他到过哪些地方的程序。在这个程序中,可在用户输入‘quit’后使用break语句立即退出while循环。'''

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(f"I'd love to go to {city.title()}!")
#在任何Python循环中都可以使用break语句。
#--------------------------------------------------------
# 7.2.5 在循环中使用continue
#要返回循环开头,并根据条件测试结果决定是否继续执行循环,可使用continue语句,他不像break语句那样不再执行余下的代码并退出整个循环。
'''例如,来看一个一数到十但只打印'奇数的循环。'''

number = 0
while number <10:
    number += 1
    if number % 2 == 0:
        continue
    print(number)
#7.2.6 避免无限循环
#每个while循环都必须有停止运行的途径,这样才不会没完没了的执行下去。
'''例如,下面从1到5:'''

x = 1
while x <= 5:
    print(x)
    x += 1    #这一行不能忘记,否则会无限循环下去。
#7.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)
    #x显示所有已验证的用户。
print("\nThe following users have been confirmed:")
for confirmed_user in confirmed_users:
    print(confirmed_user.title())
#7.3.2 删除为特定值的所有列表元素
'''假设在列表中有多个值为‘cat’的元素。要删除所有这个元素,可不断运行while循环,直到列表中不含‘cat’的值。'''
pets = ['dog','cat','dog','cat','rabbit','cat']
print(pets)
while 'cat' in pets:
    pets.remove('cat')
print(pets)

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值