For Your "A" (Request help understanding 'or')


#1

Python Loops 12

Not so much a problem completing the exercise, more understanding the "or" and why it doesn't seem to work out as I expected when I use it here.

phrase = "A bird in the hand..."

# Add your for loop
for char in phrase:
    if char == "a" or "A":
        print 'X',
    else:
        print char,

Output is just

X X X X X X X X X X X X X X X X X X X X X

I'm also curious why, if I bracket like this

if char ==( "a" or "A"):

the output is:

A   b i r d   i n   t h e   h X n d . . .

Thanks for your assistance.


#2

Hi,

Try
if char == "a" or char == "A":

The Boolean operater "or" is used to compare two complete conditionals

a short cut you can use for this situation is:

If char in "aA":

for you second question, I think it is only looking for a "a", and the "or" operator isn't valise in the parentheses(or without a complete conditional)

This also should work:

If (char == "a") or (char == "A"):

Sorry it is not formatted correctly, I am on mobile


#3

Helps a lot. Thank you!


#4

You are welcome! It's my pleasure!


#5

Hi, thanks for the solution! I had the same problem. But I still don't understand how the code is working that if I use
if char == "a" or "A":

it will print
X X X X X X X X X X X X X X X X X X X X X
It looks like it only takes the first if condition into account, always evaluates it True and never gets to else line. Could somebody please explain this?


#6


#7

You are really close!

if char = "a" or "A" will print a bunch of X's.

The boolean "or" is the key. It is creating two different conditions in the if statement. That if statement is basically saying that if char is equal to 'a' turn it into 'X' or if ANY of the characters in the phrase are 'A' turn them all into 'X'.

The interpreter is reading: if (char == 'a') or "A" then print 'X'. The same thing would happen if you were to write if char == ('a' or 'A') because python doesn't care about the parentheses.

if char == 'a' or char == 'A' is correct because it will evaluate each char in the for loop one by one and if it finds a character that is either 'A' or 'a' it will change just that character.


#8

what is this mean remove that coma after the print