Reputation: 129
statement 1 : `
self.__hours == 0 if self.__hours == 23 else self.__hours=+1
statement 2 :
if self.__hours == 23 :
self.__hours == 0
else :
self.__hours += 1
Is it just the styling or anything else ?
Upvotes: 1
Views: 178
Reputation: 1165
Setting syntax errors aside, the spirit of your two statements are generally equivalent. The first is a "conditional expression" (also called a "ternary expression").
self.__hours = 0 if self.__hours == 23 else self.__hours + 1
You are setting self.__hours
to something -- either 0
or self.__hours + 1
-- depending on the current value of self.__hours
.
The equivalent if
statement would be:
if self.__hours == 23:
self.__hours = 0
else:
self.__hours = self.__hours + 1
(self.__hours = self.__hours + 1
can also be replaced with self.__hours += 1
.)
Upvotes: 0
Reputation: 36474
In general, they're going to provide equivalent answers and be interchangeable.
One obvious difference between the two forms is that the ternary form can be used in places where an expression can be used as the body of a lambda, while the second one can't:
>>> x = lambda y: 0 if y > 0 else -1
>>>
>>> x(1)
0
>>> x(-1)
-1
or
>>> def fn(val):
... print val
...
>>> y = 2
>>> fn(0 if y > 0 else -1)
0
Upvotes: 1