>>> inputs = list() >>> while True: ... current = input("your input:") ... if current == "quit": ... break ... inputs.append(current) ... your input:a your input:b your input:test your input:quit >>> inputs ['a', 'b', 'test']
使用赋值操作符时:
1 2 3 4 5 6 7 8 9 10
>>> inputs = list() >>> while (current := input("your input:")) != "quit": ... inputs.append(current) ... your input:a your input:b your input:test your input:quit >>> inputs ['a', 'b', 'test']
此例子,省略了一条语句,可读性上升。
再来一个例子
最初版本
1 2 3
a = [1,2,3,4] if len(a) > 3: #计算 len(a) 一次 print(f"a is too long ({len(a)} elements,expected < 3)") # 计算 len(a) 第二次
我们改写为:
改进版本
1 2 3 4
a = [1,2,3,4] n = len(a) # 计算一次len(a) if n > 3: # 多了变量n print(f"a is too long ({n} elements,expected < 3)") #
新特性重写: 重写版本
1 2 3
a = [1,2,3,4] if (n:=len(a)) > 3: # 计算一次len(a),多了变量n,把两行改为一行 print(f"a is too long ({n} elements,expected < 3)") #