0
if (n=2+3)==5:
    print(n)

I executed the above code in python but it was showing an error in "if condition"`. I want to know whether there is a way to achieve writing the initilization statement in "if condition".

  • 1
    No, it will automatically detect the single = sign in the if statement and throw an error. It works somewhat in loops but not the way you have it here. – ItsLogic Jan 31 '20 at 17:34
  • 2
    In Python 3.8 - https://docs.python.org/3/whatsnew/3.8.html#assignment-expressions – wwii Jan 31 '20 at 17:35
  • Does this answer your question? [“:=” syntax and assignment expressions: what and why?](https://stackoverflow.com/questions/50297704/syntax-and-assignment-expressions-what-and-why) – wwii Jan 31 '20 at 17:38

2 Answers2

1

Basically what you can place after the 'if' keyword is an expression that either evaluates to true or false. This expression is made up of comparison and logical operators. Ther is no scope for using an assignment operator here. Even if you are thinking of doing that you are following a bad programming practice. Good programming practices are always appreciated so avoid bad ones.Thanks!

Mahyar Ali
  • 11
  • 3
0

In python,we can use walrus operator ( := ) but it was introduced in python 3.8 , so it works only in python 3.8 or latter versions.

if (n:=2+3)==5: print(n)

This works fine and gives output as you expected.