Python编程基础:循环、函数、模块等核心知识详解
1. 循环结构
循环常用于需要重复执行特定代码块的场景,Python 中有两种主要的循环类型: for
循环和 while
循环。
1.1 for
循环
for
循环是 Python 中的复合语句,其结构如下:
# sequence 可以是 range、list、set、dict、string 等
for variable in sequence: # 头部
statement 1
statement 2
...
statement n
示例:判断列表中的数字是奇数还是偶数
x = [1, 5, 8, 9, 109]
for i in x:
if i % 2 == 0:
print('the number ' + str(i) + ' is even')
else:
print('the number ' + str(i) + ' is odd')
输出结果:
the number 1 is odd
the number 5 is odd
the number 8 is even
the number 9 is odd
the number 109 is