我的作业计划几乎完成了所有内容。最后一个功能是让程序显示在输入中找到的特定元音。例如:
Please enter a word: look
The vowels in your word are
o
o
there were 2 vowels
I'm terribly sorry if I missed any 'y's.
代码:
def main():
vowels = ["a","e","i","o","u"]
count = 0
string = input(str("please enter a word:"))
for i in string:
if i in vowels:
count += 1
print("The vowels in your word are:")
print("There were",count,"vowels")
print("Sorry if I missed any 'y's")
if __name__ == "__main__":
main()
答案 0 :(得分:2)
你所缺少的就是在找到它们时保留一串元音。这很像计算元音。从"基值开始#34;一个字符串,空字符串。每次找到元音时,将(连接它)添加到字符串中。例如:
vowels_found = ""
for i in string:
if i in vowels:
vowels_found += i
print(vowels_found)
print(len(vowels_found))
在此之后,在您计划的位置打印vowels_found
。如果你想要它们在单独的行上,就像你发布的样本一样,那么在循环中打印每个,并且根本不使用vowels_found
。
在python中有更高级,更直接的方法:你可以在一个语句中包含过滤,这个例程基本上是两行:一个用于收集元音,另一个用于计数和打印它们。在课堂上稍后担心那些......但如果有人发布这些解决方案,请注意。 : - )
答案 1 :(得分:0)
您可以在if
内添加打印声明。这样,当找到元音时,它将以您在问题中显示的方式打印。
请注意,您需要将print("The vowels in your word are:")
移至if
之前,以便在元音之前打印。
例如
def main():
vowels = ["a","e","i","o","u"]
count = 0
string = input(str("please enter a word:"))
print("The vowels in your word are:") #puts text before the vowels printed in `if`
for i in string:
if i in vowels:
count += 1
print (i) #prints the vowel if it is found
print("There were",count,"vowels")
print("Sorry if I missed any 'y's")
if __name__ == "__main__":
main()