首页 > 解决方案 > 我可以浓缩这个吗?

问题描述

invalid_characters = ["1","2","3","4","5","6","7","8","9","0"]
vowels = ["a","e","i","o","u"]

letter = str(input("Enter a letter: "))
while letter in invalid_characters:
    letter = input("You entered an invalid character. Please enter a letter: ")
if letter in vowels:
    print("The letter is a vowel")
else:
    print("The letter is a consonant")

标签: python

解决方案


如果你的意思是你想让你的代码更短,试试这个:

vowels = "aeiou"

letter = str(input("Enter a letter: "))
while letter.isdigit():
    letter = input("You entered an invalid character. Please enter a letter: ")
if letter in vowels:
    print("The letter is a vowel")
else:
    print("The letter is a consonant")

但是,请记住,如果您输入“$”或任何其他特殊符号,它会说它是一个辅音。

如果你想让它更快一点,就像让-弗朗索瓦·法布尔提到的那样,你可以使用一in加快速度。

vowels = set("aeiou")

letter = str(input("Enter a letter: "))
while letter.isdigit():
    letter = input("You entered an invalid character. Please enter a letter: ")
if letter in vowels:
    print("The letter is a vowel")
else:
    print("The letter is a consonant")

推荐阅读