Python基础 - 流程控制语句

Python基础 - 流程控制语句

流程控制工具

  1. if语句

if语句是最流行的流程控制语句,可以有0个或多个elif部分,还有一个else部分可选。elif是else if的简写,if…elif…elif…语句可以用来替代其他语言的switch/case语句。

>>> x = int(input("请输入一个整数: "))
请输入一个整数: 24
>>> if x < 0:
...     x = 0
...     print('负数变成0')
... elif x == 0:
...     print('0')
... elif x == 1:
...     print('1')
... else:
...     print('更多')
  1. for语句

python的for循环可以遍历任何序列,包括集合或字符串;如果想要在遍历的同时修改序列,首先做一个副本,遍历序列的时候不会隐式创建一个副本。

# 输出序列中各个单词的长度
>>> # 测试一些字符串:
... words = ['cat', 'window', 'defenestrate']
>>> for w in words:
...     print(w, len(w))
...
cat 3
window 6
defenestrate 12
# 使用slice做列表副本,遍历的同时新增
>>> for w in words[:]: 
...     if len(w) > 6:
...             words.insert(0, w)
...
>>> words
['defenestrate', 'cat', 'window', 'defenestrate']
  1. range()函数

如果需要遍历数字序列,内置的range()函数可以使用,给定的终值不包括在生成的序列中。

>>> for i in range(5):
...     print(i)
...
0
1
2
3
4
range(5, 10) #不包括105 through 9range(0, 10, 3) #步长30, 3, 6, 9range(-10, -100, -30) #步长-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

​ 然后,在多数场景中使用enumerate()函数更加方便。

#range()函数返回一个可遍历的对象
>>> print(range(10))
range(0, 10)
>>> list(range(5))
[0, 1, 2, 3, 4]
  1. break和continue语句,以及循环中的else语句

break语句和C语言一样,退出最内层的for或者while循环。循环语句可以包含一个else语句。

>>> for n in range(2, 10):
...     for x in range(2, n):
...         if n % x == 0:
...             print(n, '等于', x, '*', n//x)
...             break
...     else:
...         # loop fell through without finding a factor
...         print(n, '是一个素数')
...

​ 在一个try语句中,当没有异常发生时会运行else部分的语句;在一个循环语句中,当没有break发生时,运行break部分的语句。

​ continue语句用来跳过本次循环,进入下一个循环。

>>> for num in range(2, 10):
...     if num % 2 == 0:
...             print("找到一个偶数: ", num)
...             continue
...     print("找到一个数: ", num)
...
找到一个偶数:  2
找到一个数:  3
找到一个偶数:  4
找到一个数:  5
找到一个偶数:  6
找到一个数:  7
找到一个偶数:  8
找到一个数:  9
  1. pass语句

pass语句什么都不做,在语法结构上需要而实际上并不需要做什么的时候可以使用。

>>> while True:
...     pass  #忙等待键盘中断 (Ctrl+C)
...

​ pass还可以用作函数或者条件块的占位符。

>>> def initlog(*args):
...     pass   #需要被实现
...    
  1. 定义函数

我们可以创建指定边界的Fibonacci序列。

>>> def fib(n):
...     a, b = 0, 1
...     while a < n:
...         print(a, end=' ')
...         a, b = b, a+b
...     print()
...
>>> fib(2000)
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597

​ 函数中的所有变量赋值都存储在局部符号表中;而变量引用首先查找局部符号表,然后查找外围函数的局部符号表,然后查找全局符号表,最后查找内置名称表。因此,全局变量不能在函数中直接赋值(除非在global语句中命名),尽管它们可以被引用。函数调用的实参在被调用函数的局部符号表中引入;因此,参数是通过值调用传递的(其中值总是一个对象引用,而不是对象的值)。当一个函数调用另一个函数时,将为该调用创建一个新的局部符号表。函数定义在当前符号表中引入函数名。函数名的值具有解释器识别为用户定义函数的类型。该值可以赋给另一个名称,该名称也可以用作函数。

>>> fib
<function fib at 0x0000023182963E18>
>>> f = fib
>>> f(100)
0 1 1 2 3 5 8 13 21 34 55 89

​ 实际上,就算函数没有return语句,也会返回一个None。

>>> fib(0)
>>> print(fib(0))
None
>>> def fib2(n):  # 返回Fibonacci序列
...     """Return a list containing the Fibonacci series up to n."""
...     result = []
...     a, b = 0, 1
...     while a < n:
...         result.append(a)    
...         a, b = b, a+b
...     return result
...
>>> f100 = fib2(100)    
>>> f100                
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
  1. 定义函数的补充

定义函数时可以指定可变参数。

  • 默认参数值

    可以指定给一个或多个参数指定默认值,这将创建一个函数,该函数可以使用比定义允许的更少的参数来调用。默认值只能被计算一次。当默认值是一个可变对象(如列表、字典或大多数类的实例)时,这就会有所不同。

    指定一个参数: ask_ok(‘Do you really want to quit?’)

    指定一个可选参数: ask_ok(‘OK to overwrite the file?’, 2)

    指定所有参数: ask_ok(‘OK to overwrite the file?’, 2, ‘Come on, only yes or no!’)

def ask_ok(prompt, retries=4, reminder='Please try again!'):while True:ok = input(prompt)if ok in ('y', 'ye', 'yes'):return Trueif ok in ('n', 'no', 'nop', 'nope'):return Falseretries = retries - 1if retries < 0:raise ValueError('invalid user response')print(reminder)
def f(a, L=[]):L.append(a)return Lprint(f(1))
print(f(2))
print(f(3))[1]
[1, 2]
[1, 2, 3]

​ 如果不想默认值在子序列中共享,可以指定空值。

def f(a, L=None):if L is None:L = []L.append(a)return L
  • 关键字参数

    函数也可以使用关键字参数,采用kwarg=value的形式。

def parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'):print("-- This parrot wouldn't", action, end=' ')print("if you put", voltage, "volts through it.")print("-- Lovely plumage, the", type)print("-- It's", state, "!")
  • 任意参数列表

    最不常用的选项是指定可以用任意数量的参数调用函数。这些参数将被包装在一个元组中。在可变数量的参数之前,可能会出现零个或多个普通参数。

def write_multiple_items(file, separator, *args):file.write(separator.join(args))>>> def concat(*args, sep="/"):
...     return sep.join(args)
...
>>> concat("earth", "mars", "venus")
'earth/mars/venus'
>>> concat("earth", "mars", "venus", sep=".")
'earth.mars.venus'
  • 拆箱参数列表

    如果参数已经在列表或元组中,但需要对需要单独位置参数的函数调用进行解包,则会出现相反的情况。

>>> list(range(3, 6))            # normal call with separate arguments
[3, 4, 5]
>>> args = [3, 6]
>>> list(range(*args))            # call with arguments unpacked from a list
[3, 4, 5]
  • Lambda表达式

    可以使用lambda关键字创建小型匿名函数。

>>> def make_incrementor(n):
...     return lambda x: x + n
...
>>> f = make_incrementor(42)
>>> f(0)
42
>>> f(1)
43
  • 文档字符串
>>> def my_function():
...     """Do nothing, but document it.
...
...     No, really, it doesn't do anything.
...     """
...     pass
...
>>> print(my_function.__doc__)
Do nothing, but document it.No, really, it doesn't do anything.
  • 函数注释
>>> def f(ham: str, eggs: str = 'eggs') -> str:
...     print("Annotations:", f.__annotations__)
...     print("Arguments:", ham, eggs)
...     return ham + ' and ' + eggs
...
>>> f('spam')
Annotations: {'ham': <class 'str'>, 'return': <class 'str'>, 'eggs': <class 'str'>}
Arguments: spam eggs
'spam and eggs'


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部