1. for循环
Python的for语句有点特别,只能对序列和字符串进行处理,序列自然包括list、tuple和range对象。
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# 练习for语句def loop_for():names = ['Tom', 'Jack', 'Black']for name in names:print(name)s = 'abc'for c in s:print(c)for n in range(3):print(n)for n in range(0, 10, 3):print(n)def main():loop_for()if __name__ == '__main__':main()
2. break、continue和else
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# 练习for语句def loop_for():names = ['Tom', 'Jack', 'Black']for name in names:print(name)s = 'abc'for c in s:print(c)for n in range(3):print(n)for n in range(0, 10, 3):print(n)def loop_continue():for num in range(2, 10):if num % 2 == 0:print('Found an even number:', num)continueprint('Found an odd number:', num)def loop_break_else():for n in range(2, 10):for x in range(2, n):if n % x == 0:print(n, 'equals', x, '*', n//x)breakelse:print(n, 'is a prime number')def main():loop_for()loop_continue()loop_break_else()if __name__ == '__main__':main()
continue语句让执行流程直接跳到for循环下一步,break语句直接从for循环终止,而else比较有意思,是当for循环不是break终止而结束的,则流程会执行到else代码块。
其它语言是没有for-else的,要实现这个else非得加一个布尔变量来判断,Python搞了一点语法糖,让开发人员稍微方便了一点。
3. while循环
while后面是一个表达式,只要结果能成为布尔值就行。
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# 练习while循环def main():n = 10while True:print('n=', n)n -= 1if n <= 0:breaki = 0while i < 5:print('i=', i)i += 1if __name__ == '__main__':main()
while一般两种常见用法:一种是直接while True,结束循环的控制条件全部放到while执行体;另一种就是while 【条件表达式】, 不满足条件时退出循环。
4. 结束语
Python循环控制语法提供了for和while,基本和C/C++/Java差不多,但是细节上有区别,比如for循环对序列对象进行迭代,for循环支持else,这个是特有的。