Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can we have assignment in a condition?

Tags:

python

Is it possible to have assignment in a condition?

For ex.

if (a=some_func()):     # Use a 
like image 796
Vishal Avatar asked Apr 08 '10 22:04

Vishal


People also ask

Can we use assignment operator in if condition?

Using the assignment operator in conditional expressions frequently indicates programmer error and can result in unexpected behavior. The assignment operator should not be used in the following contexts: if (controlling expression)

Can we assign values in if condition?

Yes, you can assign the value of variable inside if.

What does assignment in conditional expression mean?

It means you try to assign a value whereas,in the same time, you try to compare these values. To compares two values it's '==' or '==='. To assign a value to a variable it's '=' Submitted by Clarisse.

Why can't I use an assignment in an expression?

The error is a simple typo: x = 0, which assigns 0 to the variable x, was written while the comparison x == 0 is certainly what was intended.


1 Answers

Why not try it out?

>>> def some_func(): ...   return 2 ...  >>> if (a = some_func()):   File "<stdin>", line 1     if (a = some_func()):           ^ SyntaxError: invalid syntax 

So, no.

Update: This is possible (with different syntax) in Python 3.8

if a := some_func(): 
like image 83
Jason Hall Avatar answered Oct 17 '22 10:10

Jason Hall