Using 'Or'

Steven D'Aprano steve at pearwood.info
Sat Jan 16 06:07:38 EST 2016


On Sat, Jan 16, 2016 at 7:24 AM, Kitten Corner <joshua.shapo at gmail.com>
wrote:
> Hi, I have python version 3.5.1 and I am working on a project, I'm trying
> to make it by using the 'or' sequence, I'm trying to make it do 1 thing
> or the other, here's an example: print('i like pie' or 'i like donuts'),
> it only does the thing that's before the 'or', please help!


It's hard to say what is wrong if you don't tell us what you expect. What
*do* you expect 

print('i like pie' or 'i like donuts')

to print?

(1) Always the first;

(2) Always the second;

(3) Read my mind and tell me whether I want pie or donuts right now;

(4) Randomly pick one;

(5) Something else?


I can tell you that number (3) is never going to happen :-)

My guess is that you want number (4), is that right? Unfortunately, that's
not what `or` does in Python. To print a random string in Python, probably
the best way is this:


import random
choices = ["I like pie, mmmm, pie!", 
           "I like donuts. Sweet, delicious donuts.",
           "I like cookies. Gimme more cookies!",
           "I like liver and onions. With extra liver. Hold the onions."]
print(random.choice(choices))



`or` operates differently. It takes two arguments, and it picks the first
one which is "truthy". (Truthy means "true, or something kinda like true".)
Now obviously Python cannot possibly tell whether you *actually do* like
pie or not, so what does "truthy" mean here?

In Python's case, it takes the empty string "" as false, and all other
strings as true. So:


py> "hello" or "goodbye"  # choose the first truthy string
'hello'
py> "goodbye" or "hello"
'goodbye'
py> "" or "something"
'something'


Think of `or` as the following:

- if the first string is the empty string, return the second string;
- otherwise always return the first string.




-- 
Steven




More information about the Python-list mailing list