Python基础之循环语句(02)

Python中的循环语句有 for 和 while。

Python循环语句的控制结构图如下所示:

1.While循环

Python中while语句的一般形式:

while 判断条件:
    语句

注:

需要注意冒号和缩进。在Python中没有do..while循环

#0到100求和
i=0
sum=0
while i<=100:
    sum=sum+i
    i=i+1
print (sum)

while 循环使用 else 语句,在 while … else 在条件语句为 false 时执行 else 的语句块。

count = 0
while count < 5:
   print (count, " 小于 5")
   count = count + 1
else:
   print (count, " 大于或等于 5")

 

2.for循环语句

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

for循环的一般格式如下:

for <variable> in <sequence>:
    <statements>
else:
    <statements>

同样需要注意冒号和缩进

student=[{"name":"WWW"},
    {"name":"Ahab"}]
#搜索指定的姓名
find_name="WWW"
for stu in student:
    print(stu)
    if stu["name"] == find_name:
        print("找到了%s"%find_name)
        break
else:
    print("没有这个人")
print("循环结束")

这段代码中有一个知识点是下次更新的内容,如下:

student=[{"name":"WWW"},
    {"name":"Ahab"}]

感兴趣的可以先看看。

3.range()函数

python 中的range() 函数可创建一个整数列表,一般用在 for 循环中。

函数语法:

range(stop)
range(start, stop[, step])

参数说明:
    start: 计数从 start 开始。默认是从 0 开始。例如range(5)等价于range(0, 5);
    stop: 计数到 stop 结束,但不包括 stop。例如:range(0, 5) 是[0, 1, 2, 3, 4]没有5
    step:步长,默认为1。例如:range(0, 5) 等价于 range(0, 5, 1)

其实Python 的 for i in range (m,n),相当于 C++/Java/C# 里面的 for (int i = m;  i < n; i++)

for i in range(5):
  print(i)

输出 0 1 2 3 4

for i in range(5,9):
  print(i)

输出 5 6 7 8

4.break和continue函数

break 语句可以跳出 for 和 while 的循环体。如果你从 for 或 while 循环中终止,任何对应的循环 else 块将不执行。简言之break 退出循环 不再执行后续重复的代码。

i=0
while i<10:
    if i==3:
        break
    print (i)
    i+=1

continue语句被用来告诉Python跳过当前循环块中的剩余语句,然后继续进行下一轮循环。简言之continue  并没有退出循环 不执行后续重复代码

i=0
while i<=10:
    if i==3:
    # 注意死循环  确认循环的计数是否修改 i==3
        continue 
    print (i)
    i+=1

5.pass语句

Python pass是空语句,是为了保持程序结构的完整性。

pass 不做任何事情,一般用做占位语句.

for i in range(5):
    pass

小练习使用循环嵌套实现9*9乘法表:

row =1
while row<=9:
    col=1
    while col<=row:
        print ("%d*%d=%d" %(col,row,col*row),end=" ")
        col+=1
    print(" ")
    row +=1

这个不做分析有c或者java基础的都会写这段代码。

小科普:

print语句不换行,在python 3.x版本 end="" 可使输出不换行。
在python 2.x版本中,使用“,”(不含双引号)可使输出不换行

print("*",end="")  3.x
print("*"),        2.x

文章首发公众号【Ahab杂货铺】关注公众号技术分享第一时间送达!

猜你喜欢

转载自blog.csdn.net/sinat_34576567/article/details/83546712