python学航_循环

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/xuehangpy/article/details/90200288

while 循环

标准写法
while 判断条件:
    语句

无限循环写法
while True:
    语句 
    
while 循环使用 else 语句
在 while … else 在条件语句为 false 时执行 else 的语句块:
while True:
    语句 
else:
    语句

for 语句

Python for循环可以遍历任何序列的项目,如一个列表或者一个字符串。

for i in 列表,字典,字符串
    print(i)
sites = ["Baidu", "Google","Runoob","Taobao"]
for site in sites:
    if site == "Runoob":
        print("菜鸟教程!")
        break       #break 如果条件为真 跳出循环
    print("循环数据 " + site)
else:
    print("没有循环数据!")
print("完成循环!")

range()函数

如果你需要遍历数字序列,可以使用内置range()函数。它会生成数列.

range(参数1,参数2,参数3) 起始, 结束, 步长

len()函数参数为列表,字符串,字典,的长度

for letter in 'Runoob':     # 第一个实例
   if letter == 'o':        # 字母为 o 时跳过输出
      continue             #t跳出本次循环
   print ('当前字母 :', letter)
 
var = 10                    # 第二个实例
while var > 0:              
   var = var -1
   if var == 5:             # 变量为 5 时跳过输出
      continue
   print ('当前变量值 :', var)
print ("Good bye!")

猜你喜欢

转载自blog.csdn.net/xuehangpy/article/details/90200288