简体   繁体   中英

How are the letters deleted from this "Vowel eater"?

word = input("enter a word: ")
word = word.upper()


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

If I used Joseph as an example, it would return JSPH but I have no idea how the vowels are "deleted"

The letter variable takes one character from the input and compares using the if-else statement. If the character matches the vowels the letter is not printed.

That means the program is only printing the non-vowel characters.

For continue , it essentially skips to the end of the loop and starts the next loop, so following through your loop:

  1. Look at the current letter
  2. If the current letter is a vowel, then continue . (This skips to the next letter in the loop, so the line print(letter) will not be run).
  3. If the current letter is not a vowel, it reaches the else statement and prints the letter.

This means that in the end, the program only prints letters which are not vowels, as whenever a vowel is reached continue is run meaning it skips to the next letter (so the letter is not printed).

Side note: even if you didn't use continue in each elif statement, and used maybe pass instead (which is just a "blank" instruction), the code would still work as by entering one of the if or elif options in the if statement, it means that it won't run any of the other elif or else s afterwards, so the print(letter) wouldn't be called either way. A better way to show the use of continue would be to place the print(letter) outside and after the if statement.

Use regex

word = input("enter a word: ")
word = word.upper()

import re
re.sub("[AEIOU]","", word)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM