Krischu
Krischu

Reputation: 1125

if statement with inline assignment in python3 ( assignment expression )

Given the following statement in python (3):

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

Isn't it possible (like in C)?

Upvotes: 1

Views: 670

Answers (1)

Jan Wilamowski
Jan Wilamowski

Reputation: 3599

This is called assignment expression and has been made possible by the introduction of the walrus operator := in Python 3.8:

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

Note however that its use is not without controversy. Always aim for readable and understandable code. The above is rather dense and would benefit from a local variable in the loop body:

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

Upvotes: 5

Related Questions