954,160 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

How does python evaluate conditional statements?

(a | b):
For what I have read in other forum post, if a is true, python doesn't evaluate b an returns a.

(a & b):
What happens with logical and? If a is false, does python evaluates b or not?

Thanks for your help.

nunos
Light Poster
47 posts since Aug 2009
Reputation Points: 10
Solved Threads: 0
 
(a & b): What happens with logical and? If a is false, does python evaluates b or not?


No. Here's the code I just used to check this:

>>> def a():
...     print 'a'
...     return False
...     
>>> def b():
...     print 'b'
...     return True
...     
>>> a() and b()
a
False
>>> b() and a()
b
a
False
>>>
jlm699
Veteran Poster
1,112 posts since Jul 2008
Reputation Points: 355
Solved Threads: 292
 

The reason I asked about the evaluation of the logical and was because of this error I keep getting.

Here's the code:

import re

m = "03-AA-12"

x = re.compile("[A-Z]{2,2}-[0-9]{2,2}-[0-9]{2,2}")

objx = x.match(m)

if (objx != None) & (objx.group() == m):
    print "yes"
else:
    print "no"


Here's the error: Traceback (most recent call last):
File "D:\Workspace\py.LAB\src\lab.py", line 9, in <module>
if (objx != None) & (objx.group() == m):
AttributeError: 'NoneType' object has no attribute 'group'

According to what was mentioned before, I can't understand why this error occurs.

Python should only evaluate objx.group() == m if objx != None is True, since it is False it should not evaluate it and this error would not occur.

To overcome this I nested two if statements, like so:

if objx != None:
    if objx.group() == m:
        print "yes"


Even though this last piece of code works I still would like to know why the error occurs.

Thanks.

nunos
Light Poster
47 posts since Aug 2009
Reputation Points: 10
Solved Threads: 0
 

The logical and in python is the and operator, not the & which is bitwise and.

Gribouillis
Posting Maven
Moderator
2,781 posts since Jul 2008
Reputation Points: 1,024
Solved Threads: 691
 
The logical and in python is the and operator, not the & which is bitwise and.


Thanks. I changed '&' to 'and' and it now works as it should.

Cheers.

nunos
Light Poster
47 posts since Aug 2009
Reputation Points: 10
Solved Threads: 0
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You