[Tutor] diferent between " "(empty string) and None as condition
Alan Gauld
alan.gauld at yahoo.co.uk
Thu Apr 23 17:45:53 EDT 2020
On 23/04/2020 20:06, Emin Kovac wrote:
> pasword = ""
> while not pasword:
> pasword = input ('Pasword: ')
>
> username = None
> while not username:
> username = input('Username: ')
> My question is when should I or what is better to use as
> condition empty string (" ") or None?
In this particular context thee is no difference and which you use is
largely a matter of taste. But...
> Anyway, what is different between an empty string and None
They are fundamentally different things. It's like asking
what is the difference between 0 and None or even between 0 and ''
They all evaluate to false in a boolean context but they
mean different things and have different values.
>>> '' is None
False
>>> None == ''
False
Sticking to strings you can use '' to test for a string that
is empty and that's exactly what you get when you read an
empty line in a file, for example. None is something else.
It is a type in its own right - NoneType. It signifies a
non-value. You normally only get a None return from a
function (that normally returns a value) if you hit an error.
Here is an example that might help.
Consider a function:
findSmallestSubString(str, start, end)
which returns the smallest substring starting with start
and ending with end within str. If there are no substrings
meeting the criteria you get an empty string back.
If there are no occurrences of start in str you get None back.
(It would probably be better if it raised a Valueerror,
but go with me here)
So we call:
result = findSmallestSubString("bandana", 'b','n') -> 'ban'
result = findSmallestSubString("bandana", 'd','b') -> ''
result = findSmallestSubString("bandana", 'c','n') -> None
Now we can test the return value and determine what the
implications are. If we simply returned '' in the last
case we wouldn't know whether there were no substrings
or whether we had passed invalid data. But both can be
used in an if test with the same outcome.
result = findSmallestSubString("bandana", 'b','n') -> 'ban'
if result:
# process the substring
else if result is None:
# oops it was bad data
else:
# handle empty string case
Finally None can be used when we don't know what type to expect.
For example if a function takes a collection as input but we don't
know what kind of collection it is. We can use None as a type neutral
marker rather than () when we want a list or [] when we want a tuple.
By using none we can examine the data and determine the type required.
I can't think of a simple example off hand, hopefully somebody else can...
--
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