Anti_vowel Nested for loop skipping iterables


#1



https://www.codecademy.com/en/courses/python-intermediate-en-rCQKw/1/2?curriculum_id=4f89dab3d788890003000096


No error messages.
The code seems to skip over letters in a string during an iterative for loop.

I got the code to work using the commented out sections. I just dont understand why the original code [as it is below] seems to randomly skip over certain variables.


def anti_vowel(test):
    ntest=[]                          
    vowel=['a','e','i','o','u','A','E','I','O','U']
    joop=""
    
    for h in test:
        ntest.append(h) 
    print ntest
    
    for i in ntest:
        print '-', i, '-'  
        #if i in vowel:
            #continue
        #else:
        #    joop=joop+i
            
        for j in vowel:          #This is where things seem to go wrong.
            if j==i:                 # With this for loop commented out the previous loop will print out all of ntest
                ntest.remove(j)
         
    print 'ntest = ',ntest
    #print joop
    #return joop
    for a in ntest:
        joop = joop + a       
    return joop
                
        
print anti_vowel("Kristian")


#2

I am a huge fan of simplifying things. That being said, you could do the function in six lines of code. It may help to eliminate some of the confusing errors.

  1. Define the function.
  2. Create an empty string for the answer.
  3. Check for each letter in the text.
  4. If the letter is not in the string of vowels (ie. "aeiouAEIOU")
  5. Add the letter to the answer
  6. Return the answer

An example of the code, as described, is:

def anti_vowel(text):
    ans = ""
    for lett in text:
        if lett not in "aeiouAEIOU":
            ans += lett
    return ans

#3

Yeah, simplest solution is best. I was more interested in why those variables were getting skipped in the first place. I think my final answer had 2 for loops and an if statement. Thanks a ton for showing me this though!


#4

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.