About conditional statement:
In Python, some values can be evaluated kinda like True
and False
even if they are not boolean values:
For instance:
if []:
print "this branch is never reached since it evaluates to False"
print "due to the empty list"
if 0:
print "same thing here"
(More info about how some data types are evaluated in a boolean expression here: http://getpython3.com/diveintopython3/native-datatypes.html#booleans)
Now, back to the following statement:
(i == 1 and 2 or 4)
Here we have a boolean expression as well. Dissecting the expression, we have the following:
(i == 1 and 2 or 4)
((i == 1) and 2) or (4) # This is the order of evaluation
Since 2 and 4 are not 0, they will always evaluate to True
Now, understanding the output: The output will be always 4 if i
is different than 1.
The reason for this is because if i == 1
the returned value is 2. The value 2 is returned because it is not necessary to evaluate the whole expression 2 or 4
since the first part is evaluated to True.
On the other hand, if i is not 1, the value 4 has to be evaluated. Because 4 is not zero, it is evaluated to True.
This is why the output is always 4 if i is different than 1
About the "ternary" operator:
Python does not have a ternary operator like in Java/C/C++ (?:) but you have a similar effect using if-else:
# value a = <value if condition is true> if <condition> else <other value>
# Example
>>> a = 2 if 1 < 10 else 0
>>> a
2
Therefore, if you wanted to print values from the range function, you should use the following:
for i in range(1,6):
print "pet%d" % i
Or maybe, printing A for even numbers and B for odd numbers:
for i in range(1,6):
print "pet%s" % ("A" if i % 2 == 0 else "B")