I suck at coding, WHY CAN'T I GET MY LOOPS TO ACTUALLY LOOP?


#1

I know I am obviously missing something, and I feel so stupid for asking, but for some stupid reason I can't get my loops to actually loop!!!

My code is below (I stopped coding for about 3 months a while ago and have started up again, so I have forgotten a lot of shortcuts, can you help me with my code?)

def anti_vowel(text):
blank = ""
for char in text:
if char == "a" or "e" or "i" or "o" or "u" or "A" or "E" or "I" or "O" or "U":
return blank
else:
return blank + char

I get this error:
Oops, try again. Your function fails on anti_vowel("Hey look Words!"). It returns "" when it should return "Hy lk Wrds!".

I would love to get an answer, it would be greatly appreciated.

And also, should I go back and review other lessons? I don't want to but I find myself constantly looking on the forums and being frustrated by not being able to figure out the code by myself, I feel so stupid some times...

AAAAUUUUUGGGGHHHH!!!!

Please help


#2

Pyhon has a very powerful operator: in

if char in "aeiouAEIOU":

We don't want to return, though. Just continue or pass

So the real problem is that you are returning inside the loop. We should be completing the loop before exiting the function.

def anti_vowel(text):
    new_word = ""
    for char in text:
        if char in "aeiouAEIOU":
            pass
        else:
            new_word += char
    return new_word

Then there is the matter of string best practices. We're advised that strings should be treated as immutable objects so changes should not be made to a string. Instead we build an array with valid inputs and then join it into a string on return. Under these constraints, your code will look something like this:

def anti_vowel(text):
    new_word = []
    for char in text:
        if char in "aeiouAEIOU":
            pass
        else:
            new_word.append(char)
    return "".join(new_word)

Now we can go one step further and write a simple if statement with not...

def anti_vowel(text):
    new_word = []
    for char in text:
        if char not in "aeiouAEIOU":
            new_word.append(char)
    return "".join(new_word)

#3

Aside:

The above is not quite what you might think. We need to equate with every operand in the expression else it will always return True. As an operand in a conditional, a letter will always be truthy. The letter itself is not evaluated, only converted to a Boolean.

if "a":            # always true

if char == 'a':    # only True for 'a'

if char == "a" or char == "e" or ...

See where that last one is going? That's what makes in so powerful.