首页 > 解决方案 > Python 帮助 - 循环

问题描述

我希望我能得到一些帮助。这个程序的重点是它应该计算用户给出的句子中的元音。我无法让它增加计数,一切都保持在零。我希望有人可以帮助我告诉我我可能在哪里弄乱了代码。它必须保持与 for 循环直接遍历字符串的非常相似的格式。我已经尝试过很多不同的方式来操纵它。如果有人能够帮助我发布我拥有的代码。谢谢!

VOWELS = 'AEIOU'
def count3(string, letter):
  count = 0
  # for loop only loops over index, don't initialize or incriminate index
  for char in string:
    #letters = string[char]
    letter_low = str.lower(letter)
    if char == letter_low:
      count = count + 1
  return (letter + " : %d" % count)
  # come back to this, not increasing count of each vowel

def main():
  print("Enter a sentence and this sentence will display its vowel count.")
  sent = input("Enter the sentence to be analyzed:  ")
  while sent:
    print("Your sentence was: " + sent)
    sent_low = str.lower(sent)
    print("\nAnalysis")

  for letter in VOWELS:
    print(count3(sent_low, letter))

标签: pythonloops

解决方案


我认为您的代码可以进行一些清理。

def count3(string):
   vowels = ['a','e','i','o','u']
   count = 0
   for char in string:
      if char in vowels:
         count += 1
   return count
def main():

   sent = input("Enter a sentence and this sentence will display its vowel count:  ")
   print("Your sentence was: " + sent)
   sent_low = sent.lower()
   vowels = count3(sent_low)
   print(f"Your string has {vowels} number of vowels")

main()

推荐阅读