It’s a very simple question. Is
if q and r:
always guaranteed to be equivalent to this?
if q:
if r:
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Python’s
andandorare short-circuiting operators, so yes: in your example, if “q” is false, then the interpreter will not evaluate “r”.edit — after a little thought it occurs to me that it’s important to note that Python’s
andandorwork kind-of like Javascript&&and||. They do not produce a boolean result. In other words, the operands (“q” and “r”) when evaluated are sort-of “internally” cast to boolean, but that’s just to see how execution should proceed. Thus, if “q” and “r” are both non-empty strings, the result ofq and ris the string value of “r”, not booleantrue. However, when used in the context given (anifstatement), theifstatement itself is going to cast the result to boolean in order to make its own control flow decision, so the answer for this example is still “yes” 🙂