首页 > 编程语言 > 详细

python基础学习笔记——循环语句(while、for)

时间:2019-01-02 11:49:12      阅读:315      评论:0      收藏:0      [点我收藏+]

while 循环

流程控制语句 while

技术分享图片

 

1、基本循环

while 条件:
      
    # 循环体
  
    # 如果条件为真,那么循环则执行
    # 如果条件为假,那么循环不执行

 

2、break

break 用于退出当层循环

num = 1
while num <6:
    print(num)
    num+=1
    break
    print("end")

 

3、continue

continue 用于退出当前循环,继续下一次循环

num = 1
while num <6:
    print(num)
    num+=1
    continue
    print("end")

4、while else

while True:
    if 3 > 2:
        print(你好)
        break
else:
    print(不好)
while True:
    if 3 > 2:
        print(你好)
print(不好)
 
# 大家看到的这个是不是感觉效果是一样的啊,其实不然
# 当上边的代码执行到break的时候else缩进后的内容不会执行

 

 

 

for循环

for循环可以用来遍历某一对象(遍历:通俗点说,就是把这个循环中的第一个元素到最后一个元素依次访问一次)。

for循环的基本结构如下:

技术分享图片

 

for循环用来遍历整个列表

#for循环主要用来遍历、循环、序列、集合、字典
Fruits=[apple,orange,banana,grape]
for fruit in Fruits:
print(fruit)
print("结束遍历")


for循环用来修改列表中的元素

#for循环主要用来遍历、循环、序列、集合、字典
#把banana改为Apple
Fruits=[apple,orange,banana,grape]
for i in range(len(Fruits)):
if Fruits[i]==banana:
Fruits[i]=apple
print(Fruits)

 



for循环用来删除列表中的元素

Fruits=[apple,orange,banana,grape]
for i in Fruits:
if i==banana:
Fruits.remove(i)
print(Fruits)

 



for循环统计列表中某一元素的个数

#统计apple的个数
Fruits=[apple,orange,banana,grape,apple]
count=0
for i in Fruits:
if i==apple:
count+=1
print("Fruits列表中apple的个数="+str(count)+"")

 


遍历字符串

for str in abc:
print(str)

 



遍历集合对象

for str in {a,2,bc}:
print(str)

 


遍历字典

for key,value in {"name":Kaina,"age":22}.items():
print("键---"+key)
print("值---"+str(value))

 

python基础学习笔记——循环语句(while、for)

原文:https://www.cnblogs.com/ellisonzhang/p/10196740.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!