[Tutor] diferent between " "(empty string) and None as condition
DL Neil
PyTutor at danceswithmice.info
Thu Apr 23 17:52:08 EDT 2020
On 24/04/20 7:06 AM, 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?
> Anyway, what is different between an empty string and None
Here's an exercise to try:
>>> value = input( "what? " )
what? # don't type anything, press the Enter key
>>> value
''
>>> type(value)
# what is the response here?
When the 'username' while-loop executes for the first time, what will be
the value and type of username?
When the 'Enter-key only' value is evaluated, what is its type and value?
So, when the 'username' while-loop is executed for the second time, will
it have the same type as before?
Does that help make your own decision about which is better (in this
situation)?
NB I like to finish the "input-prompt" with a question-mark (assuming
English-language users!) because it 'prompts' the user to understand
that (s)he should enter a value...
Complicating the issue is the question of which type-value combinations
will auto-magically convert to Boolean-type - and whether as True or as
False. This you may already understand and is thus part of your enquiry.
If not, a recommended reading topic!
Beware of either a typo or a misunderstanding (see above):
<<<...empty string (" ")>>>
what appears within the quotation marks is a "Space" character - we
can't see it, but it is very definitely there! Thus, Space is
considerably different to "" which 'contains' no characters at all and
is known as the Nulstring or "empty string"!
With my aging eyes, I rarely use either as "literal constants" inside my
active-code, simply because it is so easy to quickly mis-read! Instead,
'at the top' I declare 'constants' (in Python this is a convention
rather than a rule), eg
NULSTRING = ""
SPACE = " "
thereafter, my code is easier-on-the-eyes, if long-winded/pedantic, eg
pasword = NULSTRING
or, if you prefer
password = NULL_STRING
PS further eye-distractive criticism because the single "L" harks back
to even before ASCII code 000 (called "NUL"), but the English
word/spelling is "null". My guess is you will want to stop there -
people with a desire for technical-precision can really 'go to town' on
these distinctions...
My preference is to use None when at a stage where the value is
completely unknown (or irrelevant), eg an optional parameter for a
function. Whereas NULSTRING (or 0, or False, ...) indicates that we
'know' the value and that it has a definite meaning and purpose.
--
Regards =dn
More information about the Tutor
mailing list