1

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)?

3
  • 1
    No, that's not possible in Python. In addition, it's bad practice even in languages that do allow it.
    – Ouroborus
    Commented Oct 2, 2021 at 11:08
  • 1
    Does this answer your question? Assignment in conditional not permitted in Python?
    – Ouroborus
    Commented Oct 2, 2021 at 11:09
  • The referred link raises the same question as I put, but it doesn't supply a solution. An answer below supplies the solution in form of the "walrus" operator.
    – Krischu
    Commented Oct 4, 2021 at 10:53

1 Answer 1

5

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)
3
  • I don't quite understand what you are saying about "benefit from a local variable"? So my "dense version" would benefit from a local variable?
    – Krischu
    Commented Oct 4, 2021 at 11:02
  • @Krischu the readability benefits from it because the complex statement gets broken down into two statements that are much easier to understand, debug and modify Commented Oct 5, 2021 at 1:37
  • @Krischu have I answered your question? If I solved your issue, please consider marking the answer as accepted. Otherwise, let me know how else I can help! Commented Oct 7, 2021 at 1:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.