[Tutor] Help with 'if' statement and the concept of None

Alan Gauld alan.gauld at yahoo.co.uk
Tue May 31 18:06:47 EDT 2016


On 31/05/16 16:16, marat murad via Tutor wrote:

> program  whose code I have pasted below. The author introduced a new way of
> coding the Boolean NOT operator with the 'if' statement I have highlighted
> the relevant area,apparently this if statement actually means if money !=
> 0,which I understood,

Boolean values are either true or false.
Other values are given boolean equivalent values by Python.
eg. For strings an empty string is False, anything else is True.
For numbers 0 is False anything else is True.

So in your example:

> *if money:*
>     print("Ah I think I can make something work")
> else:
>     print("Please sit ,it may be a while")
>

The first 'if' test is saying

'if money is equivalent to True' (anything other than zero)

In effect that's the same as you said (it's like testing for != 0)
but the important difference is that it is relying
on the boolean *equivalence* of an integer value.
The same is true in your second example:

> idea of slicing also has a if statement similar to the first one,except the
> second one accepts  0 value but the first one doesn't.
> 

>     start=input("\nStart: ")
> 
>    * if start:*
>         start=int(start)

Again this is really saying if start is True and for a string
(which is what input() returns), as I said above, True means
not empty. So the string '0' is not empty and therefore True.
It's not the value of the character that matters it's the fact
that there is a character there at all.

All objects in Python have these boolean equivalent values,
for example an empty list, tuple,set or dictionary is also
considered False. As is the special value None.

> I hope i made sense.

Yes, although your subject also mentions the concept of None?
Did you have another question about that?

HTH
-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list