I'm a little confused. Why doesn't s evaluate to True in the first part,
but it does in the second? Is the first statement something different?
>>s = 'hello' s == True
False
>>if s:
print 'hi'
hi
>>>
Thanks.
Oct 25 '06
90 3408
John Salerno wrote:
I'm a little confused. Why doesn't s evaluate to True in the first part,
but it does in the second? Is the first statement something different?
>>s = 'hello'
>>s == True
False
>>if s:
print 'hi'
"true" != "True". comparing a value to another value isn't the same
thing as interpreting a value in a specific context: http://docs.python.org/lib/truth.html
</F>
I'm a little confused. Why doesn't s evaluate to True in the first part,
but it does in the second? Is the first statement something different?
>>s = 'hello'
>>s == True
False
>>if s:
print 'hi'
The "if s" does an implicit (yeah, I know, "explicit is better
than implicit") conversion to bool, like
if bool(s):
And as such, you'll find that
bool(s) == True
You can learn more at http://docs.python.org/lib/truth.html
where you'll see that it's not really exactly a bool() call, but
that strings are a special case listed here. And if not, they
also have a __len__ method which would return zero/non-zero in
the even that strings weren't handled, making the "actual" test
(if strings weren't special-cased)
(s.__len__() <0) == True
-tkc
John Coleman wrote:
But then why is 3.0 == 3 true? They are different types.
Good question. Does one type get converted to the other automatically?
That's all I can think of...
So I suppose
>
if (10 5)
would be the same as
if (10 5) == True
because (10 5) does evaluate to "True".
Yes...and similarly,
if ((10 5) == True) == True
for the same reason...as does
if (((10 5) == True) == True) == True
as does... :*)
-tkc
Paul Rubin wrote:
"John Coleman" <jc******@franc iscan.eduwrites :
then "x == 3" is false, but "int(x) == 3" is true.
But then why is 3.0 == 3 true? They are different types.
The 3 gets converted to float, like when you say
x = 3.1 + 3
the result is 6.1.
Yes - it just seems that there isn't a principled reason for implicitly
converting 3 to 3.0 in 3.0 == 3 but not implicitly converting "cat" to
boolean in "cat" == true. There is something to be said about SML's
rigourous approach where 3.0 = 3 isn't even allowed since it is
considered ill-typed. Nevertheless, it is doubtlessly convientent to be
able to compare integers and doubles directly in the natural way and
there is little practical reason to compare a string with a truth value
so Python's solution does have common sense on its side. sk**@pobox.com schrieb:
the string class's "nil" value. Each of the builtin types has such an
"empty" or "nil" value:
string ""
list []
tuple ()
dict {}
int 0
float 0.0
complex 0j
set set()
Any other value besides the above will compare as "not false".
This list of values that are considered false is incomplete,
though. Four obvious omissions are
long 0L
unicode u""
bool False
NoneType None
Not-so-obviously, arbitrary user-defined values can also be
treated as false: If they implement __nonzero__, they are
false if False is returned from __nonzero__; otherwise,
if they implement __len__, they are false if 0 is returned
from __len__. Under these rules, array.array objects can
also be false, as can UserList and UserDict objects.
Regards,
Martin
John Coleman schrieb:
Yes - it just seems that there isn't a principled reason for implicitly
converting 3 to 3.0 in 3.0 == 3 but not implicitly converting "cat" to
boolean in "cat" == true.
Sure there is: equality should be transitive. So while we have
3 == 3L == 3.0 == 3.0+0j
and can therefore imply that 3 == 3.0+0j, we should not get
5 == True == ["foo"]
and therefore imply that 5 == ["foo"].
The phenomenon really exists only for numeric types (that two
values of different types still represent the same "thing"),
so it's not surprising that this doesn't readily extend to
other types.
In Python, there are only very few similar cases: byte strings
and unicode strings sometimes compare equal (but, since 2.5,
don't compare unequal very often); lists and tuples could be
considered to have equal values, but don't actually do compare
equal.
Regards,
Martin
Martin v. Löwis wrote:
John Coleman schrieb:
Yes - it just seems that there isn't a principled reason for implicitly
converting 3 to 3.0 in 3.0 == 3 but not implicitly converting "cat"to
boolean in "cat" == true.
Sure there is: equality should be transitive. So while we have
3 == 3L == 3.0 == 3.0+0j
and can therefore imply that 3 == 3.0+0j, we should not get
5 == True == ["foo"]
and therefore imply that 5 == ["foo"].
The phenomenon really exists only for numeric types (that two
values of different types still represent the same "thing"),
so it's not surprising that this doesn't readily extend to
other types.
In Python, there are only very few similar cases: byte strings
and unicode strings sometimes compare equal (but, since 2.5,
don't compare unequal very often); lists and tuples could be
considered to have equal values, but don't actually do compare
equal.
Regards,
Martin
Very good point, though one could argue perhaps that when one is
comparing an object with a truth value then one is implicitly asking
for the truth value of that object i.e. how it would function if used
in an if statement, etc. This would make code like 'if s: ' equivalent
to 'if s == True:' with a possible gain in readability. But - as you
demonstrate the cost of that (minimal) gain in readability would be too
high. In any event - I think it is mostly bad style to use a
non-boolean variable in 'if s:' - it reminds me too much of obscure C
code (though others might disagree).
-John Coleman
Martin v. Löwis wrote: sk**@pobox.com schrieb:
the string class's "nil" value. Each of the builtin types has such an
"empty" or "nil" value:
string ""
list []
tuple ()
dict {}
int 0
float 0.0
complex 0j
set set()
Any other value besides the above will compare as "not false".
This list of values that are considered false is incomplete,
though. Four obvious omissions are
long 0L
unicode u""
bool False
NoneType None
Not-so-obviously, arbitrary user-defined values can also be
treated as false: If they implement __nonzero__, they are
false if False is returned from __nonzero__; otherwise,
if they implement __len__, they are false if 0 is returned
from __len__. Under these rules, array.array objects can
also be false, as can UserList and UserDict objects.
A notable exception are numarray arrays (probably true for numpy too, I
haven't tested it though):
>>from numarray import array bool(array([1,2]))
Traceback (most recent call last):
File "<stdin>", line 1, in ?
RuntimeError: An array doesn't make sense as a truth value. Use any(a)
or all(a).
George
In article <11************ **********@f16g 2000cwb.googleg roups.com>,
"John Coleman" <jc******@franc iscan.eduwrote:
Very good point, though one could argue perhaps that when one is
comparing an object with a truth value then one is implicitly asking
for the truth value of that object
On the contrary -- since there is normally no need to ever
compare an object with a truth value, then I would interpret
this usage as an attempt to distinguish True or False from
other objects in general. Some kind of placeholders for
missing values, who knows. I'm not saying it's a great idea,
but it could work in recent versions of Python.
This would make code like 'if s: ' equivalent
to 'if s == True:' with a possible gain in readability. But - as you
demonstrate the cost of that (minimal) gain in readability would be too
high. In any event - I think it is mostly bad style to use a
non-boolean variable in 'if s:' - it reminds me too much of obscure C
code (though others might disagree).
Others will indeed disagree. I don't think you'll find
much support for this position. But it's not as bad as
your notion that "if s == True", where s is not a boolean
object, might represent a gain in readability. That really
redefines readability.
Donn Cave, do**@u.washingt on.edu This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: hedylogus |
last post by:
I've just begun learning C++ and I'm trying to write a program to shuffle a
deck of cards. I've succeeded....for the most part....but every now and
then rand() produces duplicate random numbers causing me to "lose" a card.
How do I avoid this??? I've attached my code below for reference. Thanks
in advance.
------------------------
#include <iostream>
#include <cstdlib>
#include <ctime>
|
by: Shaun McKinnon |
last post by:
HI...Here's my problem...I have a popup window that loads when i want it to,
but it's not sized properly. I've set the size, but it doesn't seem to
work. I've been on 8 different websites to find out what i'm doing wrong,
and so far it seems i'm doing it the right way. Here's my code...any
suggestions would be appreciated.
<script language="javascript">
<!--
window.open("256fx/index.htm", "", "height=400, width=600");
//-->
|
by: Sue |
last post by:
After finishing up my first quarter JavaScript on 12/12/03, I decided
to improve character checking on my project. In my project I only had
to do very basic validation. Therefore, I only had one function to
verify the name fields, age, email and gender.
My question is: if I create a function for each field like the code
below, what would be the best way to organize the functions and call
them? Would I need one main function and place...
|
by: James H. |
last post by:
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!
|
by: Mr Newbie |
last post by:
I am often in the situation where I want to act on the result of a function,
but a simple boolean is not enough. For example, I may have a function
called
isAuthorised ( User, Action ) as ?????
OK, this function may return a boolean, and if this is true, then no message
back is really required, but if it fails then some supporting message needs
to be returned to the calling code. As I see it there are a few options.
| |
by: Nobody |
last post by:
I've been looking for a job for a while now, and have run into this
interview question twice now... and have stupidly kind of blown it twice...
(although I've gotten better)... time to finally figure this thing out...
basically the interview question is: given an unsorted listed such as:
3,1,3,7,1,2,4,4,3
find the FIRST UNIQUE number, in this case 7... and of course the list can
be millions long...
|
by: RobG |
last post by:
I have always accessed attributes such as disabled using the DOM
element property, however I was wondering about implementing a more
generic function to get the values of attributes - which of course
leads to the DOM Element Interface's getAttribute method:
<URL: http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-666EE0F9 >
The DOM 2 Core specification says that getAttribute should return the
value of an attribute as a string, however...
|
by: cbmeeks |
last post by:
Man, I realize I've been asking a lot of questions lately.
I appreciate you guys helping me in my thought process.
This time, I have a design question I want opinions on.
I'm building a business framework for tracking trending data. I have
a class like:
class Metric
|
by: deanchhsw |
last post by:
Part A (http://bytes.com/topic/java/insights/645821-sudoku)
B (http://bytes.com/topic/java/insights/739704-sudoku-b)
C (http://bytes.com/topic/java/insights/739703-sudoku-c)
this question refers to the Sudoku howto posted on this website. The links are shown above. My question centers around the boolean variables declared in
Part A, such as the following.
boolean rows= new boolean;
...
|
by: marktang |
last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look !
Part I. Meaning of...
|
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 synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
| |
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 choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
|
by: agi2029 |
last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own....
Now, this would greatly impact the work of software developers. The idea...
|
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 into image.
Globals.ThisAddIn.Application.ActiveDocument.Select();...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
|
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.
| |
by: bsmnconsultancy |
last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...
| |