I’m learning basic Boolean logic with Python. I understand the equality operators but get confused when ands and ors get thrown in. Take a look at the following code for example:
people = 20
cats = 30
dogs = 15
if people < cats:
print "too many cats! the world is doomed!"
if people == cats or dogs == cats:
print "this is too hard"
I understand the first if statement and why it prints. i don’t know how the second if statement is evaluated. How could I change it to get that line to print?
Thanks for your help!
andrequires that all of its parts in the expression evaluate toTruefor the whole expression to beTrue.oris much less picky, as soon as any part of the expression evaluates toTruethe whole expression isTrue.You may come across the term short-circuiting in this context. It simply means that we stop evaluating expressions as soon as we can determine its outcome.
So for an
andwe can stop looking at the rest of the expression as soon as we find a part that evaluates toFalsebecause at that point the expression can never evaluate toTrue.Likewise, with
or, as soon as we find a part that’sTrue, we know the whole expression will beTrueand there won’t be a reason to look further.For the code example you posted:
if either one of these, or both of
people == cats,dogs == catsevaluated toTrue, the whole expression in theifstatement would becomeTrue. Since neither of them areTrue, the expression in theifstatement fails, i.e., isFalse, and the print statement is not executed.Finally, if you wanted to print statement to execute, you’d have to ensure that the Boolean expression evaluated to
True. One way would be to change to value ofdogsto30because thendogs == catswould beTrueand that would besufficient to make the whole expression
Trueand get the print to execute.