Greetings! I'm new to Python and am struggling a little with "and" and
"or" logic in Python. Since Python always ends up returning a value
and this is a little different from C, the language I understand best
(i.e. C returns non-zero as true, and zero as false), is there anything
I should be aware of given Python's different approach? Namely any
pitfalls or neat tricks that make the Python approach cool or save my
butt.
Thank you!
James 22 1936
James H. wrote: Greetings! I'm new to Python and am struggling a little with "and" and "or" logic in Python. Since Python always ends up returning a value and this is a little different from C, the language I understand best (i.e. C returns non-zero as true, and zero as false), is there anything I should be aware of given Python's different approach? Namely any pitfalls or neat tricks that make the Python approach cool or save my butt.
The most common use of this feature is "x = x or default_val" as a
shorthand for "if not x: x = default_val".
Also, you can emulate C's ternary operator (cond ? t : f) with
(cond and [t] or [f])[0].
James H. wrote: Greetings! I'm new to Python and am struggling a little with "and" and "or" logic in Python. Since Python always ends up returning a value and this is a little different from C, the language I understand best (i.e. C returns non-zero as true, and zero as false), is there anything I should be aware of given Python's different approach? Namely any pitfalls or neat tricks that make the Python approach cool or save my butt.
Thank you!
James
Booleans are a subtype of plain integers, so if you use them
in arithmetic expressions, they evaluate to 0 and 1. def bool():
print "Boolean algebra"
print "%9s %9s | %9s %9s %9s" % ('A','B','A and B','A or B','A xor B')
print "-"*51
for a in [False,True]:
for b in [False,True]:
print "%9s %9s | %9s %9s %9s" % (a,b,(a and b),(a or b),((a and not
b) or (not a and b)))
print
print
print "Arithmetic "
print "%9s %9s | %9s %9s %9s" % ('A','B','A + B','A * B','A - B')
print "-"*51
for a in [False,True]:
for b in [False,True]:
print "%9s %9s | %9s %9s %9s" % (a,b,(a + b),(a * b),(a - b))
bool()
Boolean algebra
A B | A and B A or B A xor B
---------------------------------------------------
False False | False False False
False True | False True True
True False | False True True
True True | True True False
Arithmetic
A B | A + B A * B A - B
---------------------------------------------------
False False | 0 0 0
False True | 1 0 -1
True False | 1 0 1
True True | 2 1 0
At 02:20 19.09.2005, James H. wrote: Greetings! I'm new to Python and am struggling a little with "and" and "or" logic in Python. Since Python always ends up returning a value and this is a little different from C, the language I understand best (i.e. C returns non-zero as true, and zero as false), is there anything I should be aware of given Python's different approach? Namely any pitfalls or neat tricks that make the Python approach cool or save my butt.
to make sure that an operation yields a boolean value wrap a bool()
around an expression.
None, 0 and objects which's len is 0 yield False.
so you can also do stuff like that: a = [] b = [1,2,3] a or b
[1, 2, 3]
class Foo:
.... def __len__(self): return 0
.... class Bar:
.... def __len__(self): return 1
.... foo = Foo() bar = Bar() foo or bar
<__main__.Bar instance at 0x7D289940>
sven.
On Mon, 19 Sep 2005 12:16:15 +0200, sven wrote: to make sure that an operation yields a boolean value wrap a bool() around an expression. None, 0 and objects which's len is 0 yield False. so you can also do stuff like that:
Are there actually any usage cases for *needing* a Boolean value? Any
object can be used for truth testing, eg:
if the_str
is to be preferred over:
if bool(the_str)
or even worse:
if bool(the_str != "")
Or wait, I have thought of one usage case: if you are returning a value
that you know will be used only as a flag, you should convert it into a
bool. Are there any other uses for bool()?
--
Steven.
On Mon, 19 Sep 2005 23:46:05 +1000, Steven D'Aprano <st***@REMOVETH IScyber.com.au> wrote: On Mon, 19 Sep 2005 12:16:15 +0200, sven wrote:
to make sure that an operation yields a boolean value wrap a bool() around an expression. None, 0 and objects which's len is 0 yield False. so you can also do stuff like that:
Are there actually any usage cases for *needing* a Boolean value? Any object can be used for truth testing, eg:
if the_str
is to be preferred over:
if bool(the_str)
or even worse:
if bool(the_str != "")
Or wait, I have thought of one usage case: if you are returning a value that you know will be used only as a flag, you should convert it into a bool. Are there any other uses for bool()?
making an index (it's an int subclass), as in things = None, 0, 1, 0.0, 5.0, '', 'a', [], [1], {}, {1:2} for thing in things:
... print 'if %-6r would act like if %s' % (thing, ('False','True' )[bool(thing)])
...
if None would act like if False
if 0 would act like if False
if 1 would act like if True
if 0.0 would act like if False
if 5.0 would act like if True
if '' would act like if False
if 'a' would act like if True
if [] would act like if False
if [1] would act like if True
if {} would act like if False
if {1: 2} would act like if True
Regards,
Bengt Richter
Steven D'Aprano wrote: On Mon, 19 Sep 2005 12:16:15 +0200, sven wrote:
to make sure that an operation yields a boolean value wrap a bool() around an expression. None, 0 and objects which's len is 0 yield False. so you can also do stuff like that:
Are there actually any usage cases for *needing* a Boolean value? Any object can be used for truth testing, eg:
if the_str
is to be preferred over:
if bool(the_str)
or even worse:
if bool(the_str != "")
Or wait, I have thought of one usage case: if you are returning a value that you know will be used only as a flag, you should convert it into a bool. Are there any other uses for bool()?
Of course if any of the default False or True conditions are
inconsistent with the logic you use, you need to do explicit truth testing.
if val > -1:
Where 0 would be True condition.
if arg != None:
Where '' could be a True condition.
Also... you need to be careful what order you do your comparisons in as..
(1 and 2) != (2 and 1) # they are both True, but not equal.
bool(1 and 2) == bool(2 and 1)
(1 and 2) * value != (2 and 1) * value
# except if value is False.
bool(1 and 2) * value == bool(2 and 1) * value
So..
bool(a and b) * value
Would return value or zero, which is usually what I want when I do this
type of expression.
Cheers,
Ron
On Mon, 19 Sep 2005 22:31:05 +0000, Bengt Richter wrote: On Mon, 19 Sep 2005 23:46:05 +1000, Steven D'Aprano <st***@REMOVETH IScyber.com.au> wrote:
Are there actually any usage cases for *needing* a Boolean value? Any object can be used for truth testing, eg:
[snip]
making an index (it's an int subclass), as in >>> things = None, 0, 1, 0.0, 5.0, '', 'a', [], [1], {}, {1:2} >>> for thing in things:
... print 'if %-6r would act like if %s' % (thing, ('False','True' )[bool(thing)]) ...
That's a pretty artificial example though. Your general index ranges from
0 to n inclusive, where n is unlikely to be 1. That limits the usefulness
of the idiom sequence_or_map ping[bool(thing)] to a tiny set of cases.
As near as I can tell, explicitly converting objects to booleans is mostly
useful for demonstrating that booleans aren't needed for truth testing.
--
Steven.
On Tue, 20 Sep 2005 03:03:15 +0000, Ron Adam wrote: Steven D'Aprano wrote: Are there actually any usage cases for *needing* a Boolean value? Any object can be used for truth testing, eg:
[snip]
Of course if any of the default False or True conditions are inconsistent with the logic you use, you need to do explicit truth testing.
[snip]
So..
bool(a and b) * value
Would return value or zero, which is usually what I want when I do this type of expression.
That's all very interesting, and valuable advice for somebody who doesn't
understand how Python's logical operators work, but the question is, when
would you actually want that type of expression?
In practice, how often do you really care that your truth values have the
specific values 0 and 1 rather than anything false and anything true? In
what circumstances?
--
Steven.
On Wed, 21 Sep 2005 09:03:00 +1000, Steven D'Aprano <st***@REMOVETH IScyber.com.au> wrote: On Tue, 20 Sep 2005 03:03:15 +0000, Ron Adam wrote:
Steven D'Aprano wrote: Are there actually any usage cases for *needing* a Boolean value? Any object can be used for truth testing, eg:
[snip]
Of course if any of the default False or True conditions are inconsistent with the logic you use, you need to do explicit truth testing.
[snip]
So..
bool(a and b) * value
Would return value or zero, which is usually what I want when I do this type of expression.
That's all very interesting, and valuable advice for somebody who doesn't understand how Python's logical operators work, but the question is, when would you actually want that type of expression?
In practice, how often do you really care that your truth values have the specific values 0 and 1 rather than anything false and anything true? In what circumstances?
When you want to use the value as an index fed to something that has a
__getitem__ for which only the values 0 and 1 are valid, e.g., a list
or tuple of length 2, as I tried to illustrate before ;-)
Also, since values 0 and 1 are the values of a bit, you can shift it
and create a mask that encodes many logical values at once, which can
be handy for truth table stuff or perhaps indexing a 2**nbits table
rather than using a tree of nested if/elses to select values.
BTW, you asked
"Are there actually any usage cases for *needing* a Boolean value?"
^^^ ;-)
AFAIK, "one" is enough to make the answer "yes" ;-)
Of course you can use other expressions than bool(x) to get the boolean
value, but you may have to think more about whether (x and 1) will
do it, or whether you should write (x!=0) or, in case x can be None,
perhaps settle on (x and 1 or 0) as an idiom to play safe.
Well, bool(x) is safe, and less typing ;-) OTOH, it's not a hammer for all nails.
Regards,
Bengt Richter This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: Eino Mäkitalo |
last post by:
I just test in Windows XP with Python 2.4
I'd like to create a file with exclusive flag.
If file exist I try to use it, if not I'd like to create it.
Python (and underlying library) works differently with/without O_EXCL
flag. Is this okay. How I should use this.
Has somebody manual :-) ?
Eino Mäkitalo
|
by: F. Petitjean |
last post by:
I want to know if iter(iterator) returns always its argument (when
argument is an iterator)
So :
>>> iterable = range(10)
>>> it = iter(iterable)
>>> that = iter(it)
>>> that is it
True # Good!
>>> that is it is not it
|
by: vdavidster |
last post by:
Hello everyone,
I want to convert a tuple to a list, and I expected this behavior:
list(('abc','def')) ->
list(('abc')) ->
But Python gave me this behavior:
list(('abc','def')) ->
|
by: Steven Watanabe |
last post by:
I know that the standard idioms for clearing a list are:
(1) mylist =
(2) del mylist
I guess I'm not in the "slicing frame of mind", as someone put it, but
can someone explain what the difference is between these and:
(3) mylist =
|
by: Frank Millman |
last post by:
Hi all
I am developing a multi-user business/accounting application. It is
coming along nicely :-), though rather slowly :-(
I have hit an issue which will require a lot of changes to the code I
have written so far, together with an increase in complexity and all
the bad things that follow from that. Before I go ahead and make the...
| |
by: krishnakant Mane |
last post by:
hello,
searched a lot of places including google search but can't find
answers to python-rpc. I am also very new to rpc. I am very clear
about its meaning and where it is to be used, but not about how it is
done.
I have a need where I need to create a layer of business logic that
will connect to mysql database at one end and a wxpython...
|
by: brad |
last post by:
Will len(a_string) become a_string.len()? I was just reading
http://docs.python.org/dev/3.0/whatsnew/3.0.html
One of the criticisms of Python compared to other OO languages is that
it isn't OO enough or as OO as others or that it is inconsistent. And
little things such as this seem to support those arguments. Not that it
matters really......
|
by: Stodge |
last post by:
Hi folks, new to Boost Python and struggling to build a prototype at
work. I thought I'd start with a conceptual question to help clarify
my understanding. I already have a basic prototype working nicely but
I'm having a few issues, which I may post about later.
A brief functional rundown of what I'm trying to prototype. Hopefully
my...
|
by: bruno.desthuilliers |
last post by:
On 27 juin, 18:09, "John Salerno" <johnj...@NOSPAMgmail.comwrote:
For which definitions of "content" and "logic" ???
The point of mvc is to keep domain logic separated from presentation
logic, not to remove logic from presentation (which just couldn't
work). Templating systems are for presentation logic. Whether they
work by embedding an...
|
by: Hystou |
last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it.
First, let's disable language...
|
by: Oralloy |
last post by:
Hello folks,
I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>".
The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed.
This is as boiled down as I can make it. ...
| |
by: jinu1996 |
last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
|
by: tracyyun |
last post by:
Dear forum friends,
With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
|
by: isladogs |
last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM).
In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules.
He will explain when you may want to use classes...
|
by: conductexam |
last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one.
At the time of converting from word file to html my equations which are in the word document file was convert...
|
by: TSSRALBI |
last post by:
Hello
I'm a network technician in training and I need your help.
I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs.
The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols.
I succeeded, with both firewalls in...
|
by: 6302768590 |
last post by:
Hai team
i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
| |
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
| |