Python 流程控制

查看全部 Python3 基础教程

if

>>> x = int(input("Please enter an integer: "))
Please enter an integer: 42
>>> if x < 0:
...     x = 0
...     print('Negative changed to zero')
... elif x == 0:
...     print('Zero')
... elif x == 1:
...     print('Single')
... else:
...     print('More')
...
More

elif 可能有零个或多个,else 部分是可选的。elifelse if 的缩写,这避免了过度缩进。if … elif … elif … 序列用于替代其他语言中的 switchcase 语句。

while

输出 Fibonacci 数列:

>>> # Fibonacci series:
... # the sum of two elements defines the next
... a, b = 0, 1
>>> while a < 10:
...     print(a)
...     a, b = b, a+b
...
0
1
1
2
3
5
8

示例包括以下特点:

  • 多个变量可以同时分别赋值,赋值前先运算右边表达式(从左到右)。
  • 与 C 类似,Python 中任何非零值都为 true,零为 false。条件表达式还可以是字符串或列表,实际上可以是任何序列类型,序列长度非零为 true,空序列为 false。标准比较操作符与 C 中一致。
  • 循环体是缩进的,缩进是 Python 中语句分组的方式。在交互提示符位置,可以为每个缩进行输入一个 tab 或多个空格。当在交互模式下输入一个复合语句时,必须以一个空行表示输入结束。注意基本语句块中的每一行的缩进数量必须相同。
  • print() 函数可以同时输出多个表达式,输出字符串时没有引号,多个输出项之间有空格。例如
    >>> i = 256*256
    >>> print('The value of i is', i)
    The value of i is 65536
    
    参数 end 用于避免输出结束后换行,或以一个不同的字符串结束输出。
    >>> a, b = 0, 1
    >>> while a < 1000:
    ...     print(a, end=',')
    ...     a, b = b, a+b
    ...
    0,1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,
    

for

Pascal 中的迭代总是基于数字的算术过程,C 中的迭代由用户给定迭代步骤和中止条件,而 Python 的 for 语句依据任意序列(列表或字符串)中的子项,按它们在序列中的顺序来进行迭代。

>>> # Measure some strings:
... words = ['cat', 'window', 'defenestrate']
>>> for w in words:
...     print(w, len(w))
...
cat 3
window 6
defenestrate 12

在迭代过程中修改集合可能会引发错误,通常更直接的方式是迭代一个集合副本或创建一个新集合。

# Strategy:  Iterate over a copy
for user, status in users.copy().items():
    if status == 'inactive':
        del users[user]

# Strategy:  Create a new collection
active_users = {}
for user, status in users.items():
    if status == 'active':
        active_users[user] = status

range() 函数

内置函数 range() 用于生成一个等差数值序列。

>>> for i in range(5):
...     print(i)
...
0
1
2
3
4

range(10) 会生成一个包含 10 个元素的列表,但不包含终点值 10。可以指定 range 的起始值和步长,步长可以为负数。

range(5, 10)
   5, 6, 7, 8, 9

range(0, 10, 3)
   0, 3, 6, 9

range(-10, -100, -30)
  -10, -40, -70

需要迭代列表索引的话,可以结合使用 range()len()

>>> a = ['Mary', 'had', 'a', 'little', 'lamb']
>>> for i in range(len(a)):
...     print(i, a[i])
...
0 Mary
1 had
2 a
3 little
4 lamb

range() 返回的对象实际上不是一个列表,而是一个可以迭代的对象,这样节省空间。

>>> print(range(10))
range(0, 10)

可以用 list()range() 获取列表。

>>> list(range(4))
[0, 1, 2, 3]

for 语句是一种迭代结构,sum() 函数是一个迭代函数。

>>> sum(range(4))  # 0 + 1 + 2 + 3
6

循环中的 break、continue、else

break 语句和 C 中的类似,用于跳出最近的一级 forwhile 循环。
循环可以有一个 else 子句,它在 for 循环迭代完整个列表或 while 循环执行条件为 false 时执行,但循环被 break 中止的情况下不会执行。

>>> for n in range(2, 10):
...     for x in range(2, n):
...         if n % x == 0:
...             print(n, 'equals', x, '*', n//x)
...             break
...     else: # else belongs to for loop
...         # loop fell through without finding a factor
...         print(n, 'is a prime number')
...
2 is a prime number
3 is a prime number
4 equals 2 * 2
5 is a prime number
6 equals 2 * 3
7 is a prime number
8 equals 2 * 4
9 equals 3 * 3

if 语句中的 else 子句相比,循环中的 else 子句更像 try 语句中的 else 子句。
try 语句中的 else 子句在没有异常发生时运行;循环中的 else 子句在没有 break 发生时运行。

continue 语句是从 C 中借鉴来的,表示循环继续执行下一次迭代。

>>> for num in range(2, 10):
...     if num % 2 == 0:
...         print("Found an even number", num)
...         continue
...     print("Found an odd number", num)
Found an even number 2
Found an odd number 3
Found an even number 4
Found an odd number 5
Found an even number 6
Found an odd number 7
Found an even number 8
Found an odd number 9

pass 语句

pass 语句什么也不做,用于在句法上必须要有但是程序上什么都不用做的情况。

>>> while True:
...     pass  # Busy-wait for keyboard interrupt (Ctrl+C)
...

通常用于创建最小类。

>>> class MyEmptyClass:
...     pass
...

新开发代码时,pass 还能用于函数或条件体中的占位符,方便抽象代码,这里 pass 会被忽略。

>>> def initlog(*args):
...     pass   # Remember to implement this!
...




参考资料

Python3 Tutorial – More Control Flow Tools

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值