python3中带有内联赋值的if语句(赋值表达式)

Kri*_*chu 1 if-statement inline variable-assignment python-3.x

在 python (3) 中给出以下语句:

import math
for i in range(100):
    if((result = math.factorial(i)) % 10  == 0):
        print(i,"->",result)
Run Code Online (Sandbox Code Playgroud)

难道不可能吗(就像C语言一样)?

Jan*_*ski 5

:=这称为赋值表达式,通过Python 3.8 中引入的海象运算符使之成为可能:

import math
for i in range(100):
    if (result := math.factorial(i)) % 10 == 0:
        print(i, "->", result)
Run Code Online (Sandbox Code Playgroud)

但请注意,它的使用并非没有争议。始终以可读且易于理解的代码为目标。上面的内容相当密集,并且会受益于循环体中的局部变量:

import math
for i in range(100):
    result = math.factorial(i)
    if result % 10 == 0:
        print(i, "->", result)
Run Code Online (Sandbox Code Playgroud)