Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python

Logic of Python Problem

Hello. I wonder how this code can print hello. Doesnt a if statement need to be true to print out? 11 or 10 isnt more than 10 and shouldnt both be true for the if statement to be true? if 11 or 10 > 20 and 30 or 50 > 20: print("Hello")

5 Answers

You might want to group your conditions with (), like so: if (11 > 20 or 10 > 20) and (30 > 20 or 50 > 20): print("Hello") or some other way, depends on what you want to do, otherwise the last 50 > 20 will render the whole thing true.

Careful, 11 or 10 > 20 doesn't mean what you wrote, 11 is being evaluated on its own and not against the value 20. Since 11 is not 0 it will return true so the evaluation of 10 > 20 doesn't even matter in an or condition that already met a true.

What you probably want is: 11 > 20 or 10 > 20, you can't abbreviate that to 11 or 10 > 20 because it has a different meaning.

The same goes for the right part of your condition, so the full condition would look like this: if 11 > 10 or 10 > 20 and 30 > 20 or 50 > 20: print("Hello")

Hi Kazukeno,

 if 11 or 10 > 20 and 30 or 50 > 20: print("Hello")

Python performs short-circuit evaluation, so it looks at the above statement and from the left sees 11 or <something>. Since 11 is considered True in Python, Python doesn't bother even looking at anything after the first or and the whole statement resolves to True and so Python executes the subsequent block.

Hope that clears everything up for you,

Cheers

Alex

This still outputs hello when i asked each single number by themself if they were bigger then 20 if 11 > 20 or 10 > 20 and 30 > 20 or 50 > 20: print("Hello")

Can you tell me why it is the last and not the second last that makes it True?

This is how it would evaluate:

if 11 > 20 or 10 > 20 and 30 > 20 or 50 > 20: print("Hello")
if False or 10 > 20 and 30 > 20 or 50 > 20: print("Hello")
if False or False and 30 > 20 or 50 > 20: print("Hello")
if False or False and True or True
if False and True or True
if False or True
if True

So, even though the 30>20 is true, it's part of an and that needs the left side also to be true which is not the case. Try to google for the words: truth table