Home > Net >  Python exercise - don't understand how this is working
Python exercise - don't understand how this is working

Time:02-03

I got stuck on this question on the Cisco training. I got to the answer, but don't understand why it works. Why does python remove the vowels after each 'continue'?

user_word = input("Enter your word: ")
user_word = user_word.upper()

for i in user_word:
    if i == "A":
        continue
    elif i == "E":
        continue
    elif i == "I":
        continue
    elif i == "O":
        continue
    elif i == "U":
        continue
    else:
        print(i)

CodePudding user response:

It does not "remove" them, it just does not print() them.

The loop is executed for each character in the word. If it is a vowel, the current iteration is ended (see the continue statement) and the next character is considered. If it is NOT a vowel, it is printed to the output and you can "see" it.

CodePudding user response:

The reason for this is as follows:

contunue means skip the loop, in fact it is this:

The continue statement, also borrowed from C, continues with the next iteration of the loop

So any vowel a, e, i, o, u gets skipped and any consonant is printed.

by way of example, if you replace the continue keyword with your own function you would see this more clearly:

user_word = input("Enter your word: ")
user_word = user_word.upper()

# a new function to replace continue
def replace_continue():
    print('vowel is found')


for i in user_word:
    if i == "A":
        replace_continue()
    elif i == "E":
        replace_continue()
    elif i == "I":
        replace_continue()
    elif i == "O":
        replace_continue()
    elif i == "U":
        replace_continue()
    else:
        print(i)

try this code and it should be more obvious.

Here is a link to the docs: https://docs.python.org/3/tutorial/controlflow.html

CodePudding user response:

The vowels do not get removed as in deleted, they just get ignored. continue is a key word, which tells the loop to go to the next iteration. If you were to put another print in the loop, outside of the if/elif statements, it becomes more visible. You may want to check the documentation for further information

for i in user_word:
    if i == "A":
        continue
    elif i == "E":
        continue
    elif i == "I":
        continue
    elif i == "O":
        continue
    elif i == "U":
        continue
    else:
        print(i)
    print('loop end')

Using the wourd 'continous' as value the above code yields :

C
loop end
N
loop end
T
loop end
N
loop end
S
loop end
  • Related