No it's not possible to have assignments in if conditions. The reason is that assignment is a statement and cannot be part of an expression (the same applies to += -=, etc), while the 'if' statement expects an expression. The potential problem with your code above is that it evaluates stmt1 several times. You could write it this way
c = expr1
if c or expr2:
k = 7
if k == 7:
Notice that '== True' is usually not needed. I know it looks restricting if you're used to C code, but it is one of the features that make python code clear.
Thanks fellas, that was helpful. Gribouillis, It turns out that the method you outlined is actually equivalent to what I am trying to do, so I can make use of that. PyTony, I wanted to have the assignment nested in an if statement; I was hoping to avoid having to do precisely what you outlined.
It turns out that something like what's being discussed is possible. It's not equivalent, but if you design with this catch in mind, you can make your programs behave in a way which mimics the desired behavior:
l = 5
k = 7*(l == 5)
Note, that while implementing boolean algebra in such a way can come handy, it can not always replace logic. For example, if '*' in the following is not replaced with 'and', the code will return an error message.
list = range(10) # Some list
a = len(list)
b = a + 5
for l in xrange(b):
if (l < a)*(not list[l]%2):
i am using visual studio 2015 and trying to export data which i am importing through excel by the user selected Excel file. Now the importing part has been successfully completed i am using OLEDB Connection but Stuck in exporting the same data to a new Excel file. tried ...
I am creating a program that when you print an author, you must show all the information of all the books that the author has written. Add a new attribute in the Author class that will be "BooksWriting: List (Book)".
I am currently creating a simulation of a pizza ordering system in object oriented program. I have some question. the instruction and guideline is long but I will try and cut it down a lot. the instruction is to create a program that simulate a pizza restaurant using ...