[newbie questions] if conditions - if isset - if empty

Chris Angelico rosuav at gmail.com
Sat Apr 14 18:26:01 EDT 2012


On Sun, Apr 15, 2012 at 8:16 AM, Mahmoud Abdel-Fattah
<accounts at abdel-fattah.net> wrote:
> Hello,
>
> I'm coming from PHP background ant totally new to Python, I just started
> using scrapy, but has some generic question in python.
>
> 1. How can I write the following code in easier way in Python ?
> if len(item['description']) > 0:
>             item['description'] = item['description'][0]
>         else:
>             item['description'] = ''
>
>
> In PHP I can write it as follows :
> $item['description'] = (len(item['description']) > 0)
> ? item['description'][0] : '';
>
> So, is there similar way in Python ?

You mean the ternary operator? Python has it, but with rather different syntax:
item['description'] = item['description'][0] if
len(item['description'])>0 else ''

There may be other ways of achieving what you want, though; if
item['description'] is always going to be a list/tuple, you can simply
check the truthiness of it rather than explicitly checking the length
(a list or tuple evaluates as true if it has content, false if not).

> 2. How can I check if this variable defined or not, in PHP I can use
> isset();, in other way, how can I make the following syntax in Python ?
> $variable = isset($array['element']) ? true : false;

There's two somewhat different things here, and I would distinguish them thus:
1) Finding out if a variable exists (or has had a value assigned to it
- in PHP and Python, they're pretty much the same thing)
2) Finding out if an array key exists.

PHP uses isset for both. In Python, the first one doesn't make a lot
of sense. A variable doesn't exist till it's given a value, and you'll
get a NameError if you try to read from it.

The easiest way to do what you're looking for is the 'in' operator:

does_it_have_it = 'element' in some_dictionary

If that's true, then some_dictionary['element'] has a value.

Hope that helps!

ChrisA
PS. Good job moving off PHP and onto Python. It's a marked improvement. :)



More information about the Python-list mailing list