Python(十六)python循环语句for、while

181 阅读2分钟

Python为我们提供了两种循环,while和for循环。

Python中并没有PHP和C#中的foreach以及do-while循环,这个要注意。

 

除此之外,python还为我们提供了比较好玩的range函数和pass语句。

 

一:while循环

1:语法:

while 判断条件(condition):

    执行语句(statements)……

 

2:使用双层while循环嵌套实现九九乘法表

# ===========================================================
# while 双层嵌套实现九九乘法表
i = 1
while i < 10:
    j = 1
    strs = ""
    while j < 10:
        z = i * j
        strs = strs + ("%d * %d = %d\t" % ( i ,j ,i * j )  )
        j+=1
    print(strs)
    i+=1

输出:

11.png

 

3:while-else 循环语句

这个就是当while的循环语句的判断条件为false时,进入else代码块部分的逻辑。

(1):语法

while <expr>:
    <statement(s)>
else:
    <additional_statement(s)>

 

(2):示例

# ==============================================
# while-else
ff = 0;
while ff < 5:
    print("我进入了while循环体",ff)
    ff+=1
else:
    print("我进入了else循环体",ff)

输出:

我进入了while循环体 0

我进入了while循环体 1

我进入了while循环体 2

我进入了while循环体 3

我进入了while循环体 4

我进入了else循环体 5

 

 

二:for循环

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

1:语法

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

 

2:示例

strs = "hello python!";
for item in strs:
    if item == "p":
        break
    else:
        print(item)

输出:

22.png

 

三:range函数

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

1:正常使用

# 1:正常使用
for i in range(5):
    print(i)

输出:

33.png

 

2:指定区间

# 2:指定区间
for i in range(5,10):
    print(i)

输出:

44.png

 

3:指定增量

# 3:指定增量
for i in range(5,30,3):
    print(i)

输出:

55.png

 

4:结合range()和len()函数以遍历一个序列的索引

# 结合range()和len()函数以遍历一个序列的索引
lists = ['Google''Baidu''Runoob''Taobao''QQ']
for item in lists:
    print(item)

print("========================================")
print("range索引值:")

for it in range(len(lists)):
    print(lists[it])

输出:

66.png

 

四:pass语句

Pass相当于一个占位符

Python中的代码块例如if-else中if下代码块中没有代码的时候。会报错,那么这个时候,在if下的代码块添加一个pass语句。即可解决问题

示例:

a = 10
if a > 10:
    pass
else:
    print("a 小于 10")

 

以上大概就是python中的循环语句

 

注意python中的string字符串以及range函数和pass语句。

 

练习题:使用for in 和 while 输出0-100 偶数和

num = 0
total = 0
while num <= 100:
    temp = num % 2
    if temp == 0:
        total += num
    num += 1
print(total)

forTotal = 0
for item in range(101):
    temp = item % 2
    if temp == 0:
        forTotal += item
print(forTotal)

 

有好的建议,请在下方输入你的评论。