我目前正在使用此代码
word = input('Enter a word: ')
count = 0
vowels = ['a' , 'e' , 'i' ,'o' , 'u']
for char in word:
if char in vowels:
count += 1
if count == 1:
print(word + ' contains ' + str(count) + ' vowel')
elif count > 1:
print(word + ' contains ' + str(count) + ' vowels')
elif count < 1:
print(word + ' contains ' + str(count) + ' vowels')
elif word == "":
print("")
它可以正常工作,直到输入为空的空间。 而不是不产生任何东西,并结束程序,它产生了这个
Enter a word:
contains 0 vowels
任何人都可以告诉我我做错了什么或帮助我吗?
答案 0 :(得分:0)
if count == 1:
print(word + ' contains ' + str(count) + ' vowel')
elif count > 1:
print(word + ' contains ' + str(count) + ' vowels')
elif count < 1:
print(word + ' contains ' + str(count) + ' vowels')
elif word == "":
print("")
你永远不会达到最后elif
。计数始终为<1
,== 1
或> 1
(如果是数字),因此其中一个if
将触发并生成print
。
答案 1 :(得分:0)
您按错误的顺序测试:输入word == ''
,count == 0
因此条件count < 1
为True
而elif word == ""
为从不达到即可。相反,重新排序测试:
if not word: # more Pythonic equivalent to 'if word == "":'
print("")
elif count == 1:
print(word + ' contains ' + str(count) + ' vowel')
elif count > 1:
print(word + ' contains ' + str(count) + ' vowels')
elif count < 1:
print(word + ' contains ' + str(count) + ' vowels')
或者,跳过程序的其余部分以获得空输入:
word = input('Enter a word: ')
if word:
count = 0
vowels = set("aeiou") # this makes the program more efficient
...