本文实例讲述了Python基础之循环语句用法。分享给大家供大家参考,具体如下:
while 循环
Python中while语句的一般形式:while 判断条件:
statements
同样需要注意冒号和缩进。另外,在Python中没有do..while循环。
以下实例使用了 while 来计算 1 到 100 的总和:
#!/usr/bin/env python3
n = 100
sum = 0
counter = 1
while counter <&#61; n:
sum &#61; sum &#43; counter
counter &#43;&#61; 1
print("Sum of 1 until %d: %d" % (n,sum))
执行结果如下&#xff1a;Sum of 1 until 100: 5050
for语句
Python for循环可以遍历任何序列的项目&#xff0c;如一个列表或者一个字符串。for循环的一般格式如下&#xff1a;for in :
else:
Python loop循环实例&#xff1a;
>>> languages &#61; ["C", "C&#43;&#43;", "Perl", "Python"]>>> for x in languages:
... print x
...
C
C&#43;&#43;
Perl Python
>>>
以下实例for实例中使用了 break语句&#xff0c;break语句用于跳出当前循环体&#xff1a;
#!/usr/bin/env python3
edibles &#61; ["ham", "spam","eggs","nuts"]for food in edibles:
if food &#61;&#61; "spam":
print("No more spam please!")
break
print("Great, delicious " &#43; food)
else:
print("I am so glad: No spam!")
print("Finally, I finished stuffing myself")
执行脚本后&#xff0c;在循环到 “spam”时会跳出循环体&#xff1a;Great, delicious ham
No more spam please!
Finally, I finished stuffing myself
range()函数
如果你需要遍历数字序列&#xff0c;可以使用内置range()函数。它会生成数列&#xff0c;例如:
>>> for i in range(5):
... print(i)
...
0
1
2
3
4
也可以使用range指定区间的值&#xff1a;
>>> for i in range(5,9) :
print(i)
5
6
7
8
>>>
也可以使range以指定数字开始并指定不同的增量(甚至可以是负数;有时这也叫做’步长’):
>>> for i in range(0, 10, 3) :
print(i)
0
3
6
9
>>>
负数&#xff1a;
>>> for i in range(-10, -100, -30) :
print(i)
-10
-40