words = ['cat', 'window', 'defenestrate'] for w in words: print(w, len(w))
1 2 3
flag = 1 while flag: print ('欢迎访问菜鸟教程!') # while 循环体中只有一条语句,你可以将该语句与 while 写在同一行中,
循环语句可以有 else 子句
在 for 循环中,else 子句会在循环成功结束最后一次迭代之后执行。
在 while循环中,它会在循环条件变为假值后执行。
但循环被 break 终止时不执行。
1 2 3 4
for i in'makana': if i == 'a':break print(i) else:print("yeselse") #break后else不会执行
循环的技巧
1 2 3 4 5 6 7 8 9 10 11 12 13
dic = {'name': 'Alice', 'age': 17}
# 迭代key for key in dic: print(f'{key}{dic[key]}')
# 迭代values for value in dic.values(): print(value)
# 同时迭代 for k, v in dic.items(): print(k, v)
1 2 3 4 5
for i, v inenumerate(['tic', 'tac', 'toe']): print(i, v) # 0 tic # 1 tac # 2 toe
1 2 3 4
questions = ['name', 'quest', 'favorite color'] answers = ['lancelot', 'the holy grail', 'blue'] for q, a inzip(questions, answers): print('What is your {0}? It is {1}.'.format(q, a))
1 2
for i inreversed(range(1, 10, 2)): print(i)
1 2 3
basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana'] for i insorted(basket): print(i)
1 2 3
basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana'] for f insorted(set(basket)): print(f)
pass语句
pass 语句不执行任何动作。语法上需要一个语句,但程序毋需执行任何动作时,可以使用该语句
1 2 3 4 5 6 7 8
whileTrue: pass# Busy-wait for keyboard interrupt (Ctrl+C) # 创建一个最小的类 classMyEmptyClass: pass # 作函数或条件语句体的占位符 definitlog(*args): pass# Remember to implement this!
match语句
1 2 3 4 5 6 7 8 9 10
defhttp_error(status): match status: case400: return"Bad request" case404: return"Not found" case418: return"I'm a teapot" case _: return"Something's wrong with the internet"
_ 被作为 通配符 并必定会匹配成功。如果没有 case 匹配成功,则不会执行任何分支
类的部分未学习
1 2 3 4 5 6 7 8 9 10 11 12
# point is an (x, y) tuple match point: case (0, 0): print("Origin") case (0, y): print(f"Y={y}") case (x, 0): print(f"X={x}") case (x, y): print(f"X={x}, Y={y}") case _: raise ValueError("Not a point")
向case添加 if 子句,称为“约束项”
如果约束项为假值,则 match 将继续尝试下一个 case 语句块
值的捕获发生在约束项被求值之前
1 2 3 4 5
match point: case Point(x, y) if x == y: print(f"Y=X at {x}") case Point(x, y): print(f"Not on the diagonal")
函数
定义
1 2 3 4 5 6 7 8 9 10 11
deffib(n): # return Fibonacci series up to n """Return a list containing the Fibonacci series up to n.""" result = [] a, b = 0, 1 while a < n: result.append(a) # see below a, b = b, a+b return result
f100 = fib2(100) # call it f100 # write the result
return 语句不带表达式参数时,返回 None。函数执行完毕退出也返回 None。
参数
参数定义的顺序必须是:必选参数、默认参数、可变参数、命名关键字参数和关键字参数
/ 前 仅限位置
*后 仅限关键字
参数检查
1 2 3 4 5 6 7
defmy_abs(x): ifnotisinstance(x, (int, float)): raise TypeError('bad operand type') if x >= 0: return x else: return -x