Python循环语句——while、for

循环语句

​ 循环语句能够使程序代码重复执行。Python支持while和for两种循环语句。

while语句

​ while语句是一种先判断后执行的循环语句,格式如下:

while 循环条件:
	语句组
[else:
	语句组
]

​ while循环没有初始化语句,循环次数是不可知的,只要循环条件满足,循环就会一直执行循环体。while循环中可以带有else语句,else语句将在后面介绍。

for语句

​ for语句是应用最广泛、功能最强的一种循环语句。Python语言中没有c语言风格的for语句,它的for语句相等于Java中增强for循环语句,只用于序列,序列包括字符串、列表和元组。

for语句格式如下:

for 迭代变量 in 序列:
	语句组
[else:
	语句组]

while语句实例:
#coding = utf-8
#!/usr/bin/python3

i = 0

while i * i < 100_000:
    i += 1

print("i = {0}".format[i])
print("i * i = {0}".format(i * i))

输出结果如下:

i = 317
i * i = 100489
for语句实例:
#coding - utf-8
#!/usr/bin/python3

print("------范围------")
for num in range(1, 10):
    print("{0} x {0} = {1}".format(num, num * num))
print("------字符串------")
for item in 'Hello':
    print(item)
    
numbers = [43, 32, 53, 54, 75, 7, 10]

print("------整数列表------")
for item in numbers:
    print("Count is : {0}".format(item))

输出结果:

------范围------
1 x 1 = 1
2 x 2 = 4
3 x 3 = 9
4 x 4 = 8
5 x 5 = 25
6 x 6 = 36
7 x 7 = 49
8 x 8 = 64
9 x 9 = 81
------字符串------
H
e
l
l
o
------整数列表------
Count is : 43
Count is : 32
Count is : 53
Count is : 54
Count is : 75
Count is : 7
Count is : 10

for语句的range()函数是创建一个范围对象,它的取值范围是1≤range(1, 10)<10,步长默认为1,总共10个整数

发布了96 篇原创文章 · 获赞 6 · 访问量 1752

猜你喜欢

转载自blog.csdn.net/cool99781/article/details/104196303