What meaning is "if k in [0, len(n_trials) - 1] else None"?

Chris Angelico rosuav at gmail.com
Sat Dec 3 18:27:42 EST 2016


On Sun, Dec 4, 2016 at 10:11 AM, Robert <rxjwg98 at gmail.com> wrote:
> I just notice that there is a slash character (\) before the if line.
> What is it for?

Yes, that's important. The entire line of code is:

    plt.xlabel("$p$, probability of heads") \
        if k in [0, len(n_trials) - 1] else None

The backslash means "this continues on the next line". The ternary
conditional looks like this:

5 if 1 < 2 else 7

Since 1 < 2, this has the value of 5. If not, it would have the value 7.

But the expression result isn't even used. So this is better written:

if k in [0, len(n_trials) - 1]:
   plt.xlabel("$p$, probability of heads")

ChrisA


More information about the Python-list mailing list