[Tutor] the 'or' attribute

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Wed Dec 10 14:03:55 EST 2003



On Tue, 9 Dec 2003, Leung Cris wrote:

> Umm....okay , I get it. So, how can i have a variable that stores ' this
> number, or that number' ?


It depends.


We can store multiple values by collecting them in a "container".  One
example of a container is a "List":

###
>>> x = ['apple', 'orange']
>>> x
['apple', 'orange']
###


With a list, we can keep both choices grouped together, and extract each
one by just pointing to it with an "index":

###
>>> x[0]
'apple'
>>> x[1]
'orange'
###

So this would be one way of storing several values in a group.


The usage of "or" in Python is not the one you're familiar with in
English. In Python, 'or' is not really meant to present value
alternatives.  Instead, 'or' is most used for "logical" (true/false)
comparisons, within an 'if' or 'while' conditional statement.
                       ^^^^^^^^^^^^^^^


###
if sun_is_shining or rain_is_falling:
    stay_inside()
###




To see if a value is in one of several alternatives, you might be tempted
to say something like this:

###
if fruit == 'apple' or 'orange' or 'pineapple':
    ...
###

But don't do this!  *grin* It's not doing what you think it's doing.



One way to express this idea, to check if fruit is either an apple, an
orange, or a pineapple, in Python is:

###
if fruit in ['apple', 'orange', 'pineapple']:
    ...
###


Another way to say this does involve 'or', but it looks more verbose than
you'd expect:

###
if fruit == 'apple' or fruit == 'orange' or fruit == 'pineapple':
    ...
###


'or' is tricky because we use 'or' in two different senses in English.
Python uses 'or' in one particular way --- in the boolean 'true/false'
sense.



I hope this clears up some confusion!




More information about the Tutor mailing list