[Tutor] use the data None

Dave Angel d at davea.name
Tue Jun 5 04:00:52 CEST 2012

On 06/04/2012 06:14 AM, Tehn Yit Chin wrote:
> Thanks for the quick answers.
> The potential for the variable not to exists is when I am using the
> optparser module, and I want to check if a particular parameter was passed
> in or not. If the parameter was not passed in, then the variable would not
> exists. Eg
> If I call a python script is expecting a parameter "param1" but I failed to
> passed it via the command line, I would do the following check
> (options, args)=parser.parse_args()
> if options.param1 != None:
>          param1 = int(options.param1 )
> else:
>          param1 = 30
> By the way, please excuse the way I am coding, I come from a C background.
> I think I shall try the catch method.
> Thanks!
> On Mon, Jun 4, 2012 at 3:09 AM, Alan Gauld <alan.gauld at btinternet.com>wrote:
>> On 04/06/12 01:39, Alan Gauld wrote:
>>  for var in (a,b,c):
>>>    if not var:
>>>           print var.__name__, ' is empty or false'
>> Oops, that won't work. __name__ is not an attribute
>> of object, which I thought it was...
>> But hopefully the intention was clear.
>> --
>> Alan G
>> Author of the Learn to Program web site
>> http://www.alan-g.me.uk/
>> ______________________________**_________________
>> Tutor maillist  -  Tutor at python.org
>> To unsubscribe or change subscription options:
>> http://mail.python.org/**mailman/listinfo/tutor<http://mail.python.org/mailman/listinfo/tutor>
Gosh, you said the variable might not exist.  But then you're using the
code   options.param1  where param1 is an attribute, not a variable in
any sense of the word.

If you have an *attribute* that may or may not exist, you can use
getattr() function on it, and even specify your own default.

Of course, if the stuff is coming from some argument parsing logic, it
probably already handles this for you, and this is all besides the point.



More information about the Tutor mailing list