while 循环

while循环的写法

num = 1
while num <= 10:
   print(num)
   num += 1

循环不是必须要使用的,但是为了提高代码的重复使用率,所以有经验的开发者都会采用循环

 while循环的格式

while 条件:
   条件满足时,做的事情1
   条件满足时,做的事情2

 while循环的注意事项

i=i+1别忘记写,否则条件永远满足,一直执行

9. while循环应用

while循环嵌套

矩形打印代码

i = 1
while i <= 5:
    print("*****")
    i += 1

三角形代码  

只要把打印矩形的基础上把内部的while循环的条件由j<=5修改成 j<=i即可

i = 1
while i <= 5:
   j = 1
   while j <= i:
      print("*",end="")
      j += 1
   print("")
   i += 1

 while嵌套应用二:九九乘法表

i = 1
while i <= 9:
   j = 1
   while j <= i:
      print("%d*%d=%d " % (j,i,j*i),end="")
      j += 1
   print("")
   i += 1                                    添加制表符

for循环语句

while循环一样,for可以完成循环的功能。

Python中 for循环可以遍历任何序列的项目,如一个列表字符串、元组等等

 for循环的格式

for 临时变量 in 列表或者字符串等:
   循环满足条件时执行的代码

例如 输出就是竖行

 

name = 'Python'
for x in name:
   print(x)

for循环中的break

name = 'Python'
for x in name:
   print('----')
   if x == 't':
      break
   print(x)

while循环中的break

i = 0
while i< 5:
   i = i+1
   print('----')
   print(i)

i = 0
while i < 10:
   i = i+1
   print('----')

 

原文地址:https://www.cnblogs.com/kesz/p/10572582.html