[Tutor] syntax question

Carlos Hanson carlos.hanson at gmail.com
Wed May 21 19:17:14 CEST 2008


On Wed, May 21, 2008 at 5:27 AM, Eric Abrahamsen <girzel at gmail.com> wrote:
> Hi all,
>
> This is a syntax that I've seen on occasion in other people's code:
>
> theme = (VALID_THEMES[0], theme) [ theme in VALID_THEMES ]
>
> I have no idea how this works, or how to go about looking it up. Can someone
> enlighten me as to what's happening here?
>
> Many thanks,
> Eric


First, I looked at the code to see what I easily understood:

 - VALID_THEMES is a list of type something, since it has an index
applied to it:VALID_THEMES[0]
 - theme is a type something that is in the list: theme in VALID_THEMES

Next, I started playing with it based on what I knew using string as
the theme type:

--> VALID_THEMES = ['sun', 'moon', 'earth']
--> theme1 = 'moon'
--> theme2 = 'mars'
--> print (VALID_THEMES[0], theme1)
('sun', 'moon')
--> print (VALID_THEMES[0], theme2)
('sun', 'mars')
--> [theme1 in VALID_THEMES]
[True]
--> [theme2 in VALID_THEMES]
[False]
--> (VALID_THEMES[0], theme1)[theme1 in VALID_THEMES]
'moon'
--> (VALID_THEMES[0], theme2)[theme2 in VALID_THEMES]
'sun'

So what just happened? First, we created a tuple of the first
VALID_THEME and a variable theme. Then we tested the variable theme to
see if it was a VALID_THEME. The combination of the two always gives
us a valid theme.

The test if [theme in VALID_THEMES] becomes an index to the tuple:

--> (VALID_THEMES[0], theme1)[1]
'moon'
--> (VALID_THEMES[0], theme1)[0]
'sun'

But we got [True] and [False]:

--> True == 1
True
--> False == 0
True

So in words, the code returns the default theme which is the first in
the list of valid themes unless the chosen theme is also in the list
of valid themes.

My suggestion is to play with code in the interpreter that you don't understand.

-- 
Carlos Hanson


More information about the Tutor mailing list