r/Python • • Oct 27 '10

Learning Python and can't see the difference?

I started with self teaching myself HTML about 9 years ago. Since then I have moved on to taking a basic C++ class. I since have self taught myself further in C++ with some Java. I am working on teaching myself python at the moment, maybe it is late, or maybe I am just that un-educated in programming, but I can't wrap my head around why I get such different results from this short code. Could someone kindly explain, or point me to a resource that could better explain why? I am currently using www.diveintopython.org and openbookproject.net//thinkCSpy/index.html

prefixes = "JKLMNOPQ" suffix = "ack"

for char in prefixes: if char == "O" or "Q": print char + 'u' + suffix else: print char + suffix

Juack Kuack Luack Muack Nuack Ouack Puack Quack

for char in prefixes: if char == "O": print char + 'u' + suffix elif char == "Q": print char + 'u' + suffix else: print char + suffix

Jack Kack Lack Mack Nack Ouack Pack Quack

0 Upvotes

22 comments sorted by

View all comments

24

u/norwegianwood Oct 27 '10

This line,

if char == "O" or "Q":

should be,

if char == "O" or char == "Q":

Your version could be rewritten with parentheses as,

if (char == "O") or "Q":

and you will see clearly now that the condition as a whole is always True because the value Q is always equivalent to True.

2

u/jigs_up Oct 27 '10
if (char == "O") or "Q":

wouldn't that just return true every time because Q evaluates to True [not None] ?

5

u/torrible Oct 27 '10

Yep. That's why norwegianwood said "the condition as a whole is always True" and that's why the output words in the first test all had 'u' inserted.