What meaning is "if k in [0, len(n_trials) - 1] else None"?
MRAB
python at mrabarnett.plus.com
Sat Dec 3 18:51:49 EST 2016
On 2016-12-03 23:11, Robert wrote:
> On Saturday, December 3, 2016 at 6:09:02 PM UTC-5, Robert wrote:
>> Hi,
>>
>> I am trying to understand the meaning of the below code snippet. Though I have
>> a Python IDLE at computer, I can't get a way to know below line:
>>
>> if k in [0, len(n_trials) - 1] else None
>>
>> I feel it is strange for what returns when the 'if' condition is true?
>> The second part 'None' is clear to me though.
>>
>> Could you explain it to me?
>>
>>
>> thanks,
>>
>>
>> %matplotlib inline
>> from IPython.core.pylabtools import figsize
>> import numpy as np
>> from matplotlib import pyplot as plt
>> figsize(11, 9)
>>
>> import scipy.stats as stats
>>
>> dist = stats.beta
>> n_trials = [0, 1, 2, 3, 4, 5, 8, 15, 50, 500]
>> data = stats.bernoulli.rvs(0.5, size=n_trials[-1])
>> x = np.linspace(0, 1, 100)
>>
>> # For the already prepared, I'm using Binomial's conj. prior.
>> for k, N in enumerate(n_trials):
>> sx = plt.subplot(len(n_trials) / 2, 2, k + 1)
>> plt.xlabel("$p$, probability of heads") \
>> if k in [0, len(n_trials) - 1] else None
>> plt.setp(sx.get_yticklabels(), visible=False)
>> heads = data[:N].sum()
>> y = dist.pdf(x, 1 + heads, 1 + N - heads)
>> plt.plot(x, y, label="observe %d tosses,\n %d heads" % (N, heads))
>> plt.fill_between(x, 0, y, color="#348ABD", alpha=0.4)
>> plt.vlines(0.5, 0, 4, color="k", linestyles="--", lw=1)
>>
>> leg = plt.legend()
>> leg.get_frame().set_alpha(0.4)
>> plt.autoscale(tight=True
>
> I just notice that there is a slash character (\) before the if line.
> What is it for?
>
> I've learn Python for a while, but I don't use it for more than 2 years now.
> Thanks.
>
The backslash at the end of the line indicates that that the statement
continues onto the next line, so it's the same as:
plt.xlabel("$p$, probability of heads") if k in [0, len(n_trials) -
1] else None
However, that line is weird!
In Python there's a "ternary operator". The docs say:
"""The expression x if C else y first evaluates the condition, C rather
than x. If C is true, x is evaluated and its value is returned;
otherwise, y is evaluated and its value is returned."""
Suppose you have the expression:
"even" if x % 2 == 0 else "odd"
If x is a multiple of 2, that expression will evaluate to "even", else
it will evaluate to "odd".
The line in your code is misusing it as a statement. Normally you would
write this instead:
if k in [0, len(n_trials) - 1]:
plt.xlabel("$p$, probability of heads")
Why was it written that way? I have no idea, it's just weird...
More information about the Python-list
mailing list