python while循环

 while  先判断条件是否为True,然后在执行循环体

 1、循环体的控制方式

循环默认为True,如果要终止 需要用break 终止循环

复制代码
memo = "\n need pizza pl"

while True:
    ask = input(memo)

    if ask == "quit":
        break
    else:
        print(f'pizza pl is {ask}')
复制代码

 

 

continue 跳过本次循环继续往下执行

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

 

循环标识active,当满足条件时  阀值 设置为 False终止循环

复制代码
mem = "\nneed pizza pl : "
active = True

while active:
    ask = input(mem)

    if ask == "quit":
        active = False
    else:
        print(f'pizza pl is {ask}')
复制代码

 

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

 一个简单的调查问卷字典实例

复制代码
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(f"{name} would like to climb {response}.")

复制代码

 

 

习题:

将pets列表中的值移动到bigpets中,其中每移动一次就打印一次.

复制代码
pets = ['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']
bigpets = []


while pets:
    for name in pets:
        print(f' I like animal {name}')
        pets.remove(name)
        bigpets.append(name)
print(bigpets)

输出:

 

 这时会发现,虽然列表的值全部 转移到 列表bigpets中,但是顺序已经改变了,这里的问题出在 for循环中适用remove()方法,下面有错误解释;这里能够把全部元素转移过去的原因是 外层有一个while pets

循环,只要列表还有元素是就会继续执行循环,所以发生了列表元素位置的变化而值却没有短缺,,,,下面的例子会发现连值都不全

复制代码

 

错误写法:

复制代码

pets = ['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']
bigpets = []

for
name in pets: print(f' I like animal {name}') pets.remove(name) bigpets.append(name) print(bigpets)

输出:

 

 

复制代码

 

错误的地方是该在for循环遍历时,指针一直在记录着,也就是,dog第一个匹配项删除后,pets列表的第一个项目就成了cat,而for循环的指针却指向的是2,所以在删除第一个元素的后的pets新列表第二个指针就成了dog 

pets = ['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']  第一指针是dog

pets = ['cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat'] 第二指针dog

pets = ['dog', 'goldfish', 'cat', 'rabbit', 'cat'] 第三指针cat
pets = ['goldfish', 'cat', 'rabbit', 'cat'] 第四指针cat
所以输出是 dog dog cat cat

for循环是一种遍历列表的有效方式,但不应在for循环中修改列表,否则将导致Python难以跟踪其中的元素。要在遍历列表的同时对其进行修改,可使用while循环。通过将while循环同列表和字典结合起来使用
可收集、存储并组织大量输入,供以后查看和显示。

posted @   茶叶蛋蛋  阅读(197)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示