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 comparing two strings are wrong

I have the code below and when I execute I get

            print(type(checkfile_response))
            print (checkfile_response)
            print(type("audio"))
            print(checkfile_response != "video" or checkfile_response != "audio")

OUTPUT:

<type 'str'>
audio
<type 'str'>
True

shouldn't the fourth line be false since checkfile_response is "audio"? Im trying to say if checkfile_response is not video or audio do something

3 Answers

Ah, was about to say the same thing :)

a or b

is True when a is True OR b is True. So since:

"audio" != "video"

is True, your whole statement is True.

Logical OR only needs one value to be true in order to evaluate to true. So the expression:

print(checkfile_response != "video" or checkfile_response != "audio")

Becomes:

print(True or False) 

So you'll get True back. If you want them to both not be equal, you can use and.

so if I want to say:

if checkfile_response does not equal the words "video" or the words "audio"

then do something how will you express that

If you use AND to write:

print(checkfile_response != "audio" and checkfile_response != "video"))

This will check if checkfile_response is neither audio nor video. So this will return False if checkfile_response is "audio", False if it is "video" and True if it is anything else.

I'm no Python expert, but if I want to check if a value is in a set of values, or not, I use the IN keyword with a list:

if checkfile_response in ["audio", "video"]:
    #do something if it is audio or video
else:
   #do something else if not

This is particularly useful if you have a longer list so you don't have to chain together a big long line of if this == that and this == that and this == that etc.

You can also use the NOT keyword to check if it is not in the list easily, and I find it matches up with how I think a bit better:

if not checkfile_response in ["audio","video"]:
    #do something if it's not one of those