具有结束错误的Python程序

时间:2014-10-14 11:15:49

标签: python string

我目前正在使用此代码

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

任何人都可以告诉我我做错了什么或帮助我吗?

2 个答案:

答案 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 < 1Trueelif 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
    ...