Python流程控制与函数
大约 4 分钟
流程控制与函数
流程控制
if 语句:根据条件判断是否执行某些代码。if 语句后可有 0 个或多个 elif 语句,最后可跟 0 个或 1 个 else 语句。
# if、elif、else语句 age = 18 if age >= 18: print("成年人") elif age >= 12: print("青少年") else: print("未成年人")for 语句:用于遍历序列(如列表、元组、字符串等)中的每个元素。
# 常规循环 words = ['cat', 'window', 'defenestrate'] for word in words: print(word, len(word)) """ cat 3 window 6 defenestrate 12 """ # 循环对象 users = { 'Hans': 'active', 'Éléonore': 'inactive', '景太郎': 'active' } for user,status in users.copy().items(): # 操作修改时,提前copy一份进行for print(user) if status == 'active': print(user) else: del users[user] print(users)while 语句:条件为真时循环执行,条件变为假时结束。
# while语句:输出斐波那契数列中小于10的数 a, b = 0, 1 while a < 10: print(a, end=' ') a, b = b, a + b # 0 1 1 2 3 5 8 # a, b = b, a + b 为序列解包:右侧先整体求值,再依次赋值给左侧range()函数:用于生成一个整数序列,通常用于 for 循环中。
# range()函数 for i in range(5): print(i) print("------") # 指定数字开始 for i in list(range(3, 8)): # 生成[3,8)列表 print(i) # 3 4 5 6 7 print("------") # 指定步长 for i in list(range(3, 8, 2)): # 生成范围[3,8),步长为2的列表 print(i) # 3 5 7break 和 continue 语句
- break 语句:用于跳出当前最近的一个循环,不再执行后续循环。
- continue 语句:用于跳过当前循环的剩余代码,直接进入下一次循环。
# break for i in list(range(1, 10)): if i % 3 == 0: break print(i) # 1 2 # continue for i in list(range(1, 10)): if i % 3 == 0: continue print(i) # 1 2 4 5 7 8循环的 else 子句
在 for 或 while 循环中,break 语句可能对应一个 else 子句,若循环在未执行 break 的情况下结束,else 子句将会被执行。
# 循环中的else,例如找质数
for n in range(2, 10):
for x in range(2, n):
if n % x == 0:
print(n, 'equals', x, '*', n // x)
break
else:
print(n, 'is not equals')
- pass 语句:不执行任何动作
# pass语句
for i in list(range(1, 10)):
if i % 3 == 0:
pass
else:
print(i) # 1 2 4 5 7 8
while True:
pass # 无限等待键盘中断 (Ctrl+C)
- match:类似于 js 中的 switch 语句,用于根据不同的情况执行不同的代码块。
# match语句
def http_error(status):
match status:
case 400:
return 'Bad Request'
case 429:
return 'Too Many Requests'
case 500:
return 'Internal Server Error'
case 401 | 403 | 404: # 组合
return 'Not Found'
case _:
return 'Server Error'
函数
1. 定义函数
函数关键字 def
# 1. 默认值函数:默认值参数需在最后面
def defaultAruguments(prompt, render=4):
print(prompt)
print(render)
defaultAruguments('text');
print("-----2.关键字函数-----")
def keyFunction(voltage, state='online', mode='self'):
print(voltage)
print(state)
print(mode)
# 调用时使用关键字赋值
keyFunction(17, mode='ems', state='offline')
# 特殊符号,*接收任意数量的位置参数,**接收任意数量的关键字参数
def foo(foo1, foo2=10, *args, **kwargs):
print(foo1) # 1
print(foo2) # 2
print(args) # (3,4)
print(kwargs) # {'e': 5, 'f': 6, 'g': 7}
foo(1, 2, 3, 4, e=5, f=6, g=7)
2. 函数定义详解
特殊参数:*、/
- 斜杠/:仅限位置参数,在/左侧的参数只能使用位置参数的方式进行传递。
- 星号*:仅限关键字参数,在*右侧的参数必须使用关键字参数的方式进行传递。
- 组合使用/和*:/左侧的参数只能使用位置参数的方式进行传递,*右侧的参数必须使用关键字参数的方式进行传递。
# 3.特殊参数函数:*、/ def spacialFunction(interable, /, *, key=None, reverse=False): # interable只能位置传参,key、reverse只能以关键字传参 print(interable) # 位置传参:[1, 2, 3, 4, 5, 6] print(key) # 关键字传参:key print(reverse) # 默认值:False spacialFunction([1, 2, 3, 4, 5, 6], key='key')任意实参列表
# 任意实参列表 def concat(*args, sep="/"): return sep.join(args) result = concat("earth", "mars", "venus") print(result) # earth/mars/venus解包实参列表
# 解包实参列表 def parrot(voltage, state='a stiff', action='voom'): print("-- This parrot wouldn't", action, end=' ') print("if you put", voltage, "volts through it.", end=' ') print("E's", state, "!") d = {"voltage": "four million", "state": "bleedin' demised", "action": "VOOM"} parrot(**d) # d字典传入,使用**d解包Lambda 表达式:用于创建小巧的匿名函数
# lambda:创建匿名函数 def make_incrementor(n): return lambda x: x + n f = make_incrementor(42) f1 = f(1) print(f1) # 43文档字符串:用于描述函数的作用、参数、返回值等信息。
# 文档字符串:函数体第一行的字符串,通过__doc__属性读取 def my_function(): """文档字符串:说明函数的用途、参数和返回值。""" return None print(my_function.__doc__) # 文档字符串:说明函数的用途、参数和返回值。 help(my_function) # help()也会展示文档字符串函数注解:标注 是以字典形式存放在函数的
__annotations__属性中(系统学习见类型注解)def f(ham: str, eggs: str = 'eggs') -> str: print("Annotations:", f.__annotations__) print("Arguments:", ham, eggs) return ham + ' and ' + eggs f('spam')
Loading...
