put multiple condition in if statement

Steven D'Aprano steve at REMOVETHIScyber.com.au
Sat Mar 11 07:12:23 CET 2006


On Fri, 10 Mar 2006 21:47:33 -0800, Alex Martelli wrote:

> <Allerdyce.John at gmail.com> wrote:
> 
>> Hi,
>> 
>> How can I put multiple condition in if statement?
>> 
>> I try this, but I can't get that to work.
>> 
>> if ( (str != " ") && (str != "") ):
> 
> Why would you WANT to conjoin two instances of the SAME check...?!

No, the first is checking for str equal to a space character, the second
for the empty string. You need to get those glasses checked *grin* 


Note to the original poster: the more "pythonic" way of doing this check
will be:

if s and s.strip():
    # do something with non-empty s
else:
    # s is either empty or all whitespace

Don't use "str" as a variable name, as it will over-ride the built-in type
str. This will eventually cause you problems, when you try something like
this:

>>> str(5)
'5'
>>> str = "Hello world"  # shadow the built-in
>>> str(5)
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: 'str' object is not callable



-- 
Steven.




More information about the Python-list mailing list