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 returns b if true, else returns a.
  • a or b returns a if true, else returns b.

so, expression:

parameter , (" " + parameter) or "" 

which equivalent to:

(parameter , (" " + parameter)) or  "" #    a1               a2               b #                               or   b 

how expression evaluated if:

  • parameter - a1 evaluated true:

    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

Popular posts from this blog

java.util.scanner - How to read and add only numbers to array from a text file -

rewrite - Trouble with Wordpress multiple custom querystrings -