Using "and" and "or" operator with Python strings -
i don't understand meaning of line:
parameter , (" " + parameter) or ""
where parameter string
why 1 want use and
, or
operator, in general, python strings?
suppose using value of parameter
, if value none
, rather have empty string ""
instead of none
. in general?
if parameter: # use parameter (well expression using `" " + parameter` in case else: # use ""
this expression doing. first should understand and
, or
operator does:
a , b
returnsb
iftrue
, else returnsa
.a or b
returnsa
iftrue
, else returnsb
.
so, expression:
parameter , (" " + parameter) or ""
which equivalent to:
(parameter , (" " + parameter)) or "" # a1 a2 b # or b
how expression evaluated if:
parameter - a1
evaluatedtrue
:result = (true , " " + parameter) or "" result = (" " + parameter) or "" result = " " + parameter
parameter - a1
none
:result = (none , " " + parameter) or "" result = none or "" result = ""
as general suggestion, it's better , more readable use a if c else b
form expression conditional expression. so, should better use:
" " + parameter if parameter else ""
instead of given expression. see pep 308 - conditional expression motivation behind if-else
expression.
Comments
Post a Comment