009、while 循环 ,for 循环

 1、while 循环

while 判断条件(condition):
    执行语句(statements)……
    condition 条件不满足时
    退出循环(break)

示例代码如下:

n = 5
while n > 0:
    n -= 1
    if n == 2:
        break
    print(n)
print('循环结束。')

print('==================')
n = 5
while n > 0:
    n -= 1
    if n == 2:
        continue
    print(n)
print('循环结束。')
View Code

执行结果如下:

D:\SkyWorkSpace\WorkSpace\Pytest\Temp\day06\venv\Scripts\python.exe D:/SkyWorkSpace/WorkSpace/Pytest/Temp/day06/gggg/test_2.py
4
3
循环结束。
==================
4
3
1
0
循环结束。

Process finished with exit code 0
View Code

 

2、for 循环

temp = [i for i in range(1, 101)]
print(sum(temp))

print(sum(range(1, 101)))

print('=====================')

a = ['Google', 'Baidu', 'Runoob', 'Taobao', 'QQ']
for i in range(len(a)):
    print(i, a[i])
View Code

执行结果如下:

D:\SkyWorkSpace\WorkSpace\Pytest\Temp\day06\venv\Scripts\python.exe D:/SkyWorkSpace/WorkSpace/Pytest/Temp/day06/gggg/test_2.py
5050
5050
=====================
0 Google
1 Baidu
2 Runoob
3 Taobao
4 QQ

Process finished with exit code 0
View Code

 

 

补充知识:

a、循环时,continue表示 跳过后面的代码回到开始的地方, break 跳出整个代码段 ;

  break 可以 改成 return 吗?不可以,return 是函数用的 ;

b、 默认情况下 ,None 、[ ]、()、""、{}、0  都是  False  ,示例代码如下:

# None 、[]、()、""、{}、0  都是false

if None:
    print(True)
else:
    print(False)

print('==================')

if []:
    print(True)
else:
    print(False)

print('==================')

if ():
    print(True)
else:
    print(False)

print('==================')

if '':
    print(True)
else:
    print(False)

print('==================')

if {}:
    print(True)
else:
    print(False)

print('==================')

if 0:
    print(True)
else:
    print(False)
View Code

执行结果如下:

D:\SkyWorkSpace\WorkSpace\Pytest\Temp\day06\venv\Scripts\python.exe D:/SkyWorkSpace/WorkSpace/Pytest/Temp/day06/gggg/test_2.py
False
==================
False
==================
False
==================
False
==================
False
==================
False

Process finished with exit code 0
View Code

 

posted @ 2021-07-25 23:44  空-山-新-雨  阅读(65)  评论(0编辑  收藏  举报