python - 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))
解决方案
我认为您的代码可以进行一些清理。
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()
推荐阅读
- c# - 收到错误“加载项
正在尝试扩展 ,但没有任何兼容的插件定义此扩展点 - c - 如何在安装 r2dec 时修复“r_cons.h/r_types.h:没有这样的文件或目录”
- flutter - 当我将自定义小部件插入 Column / Flutter 时崩溃
- php - 如果主图像不可用,则获取另一个图像
- angular - 如何在按钮获得焦点时禁用键
- c - 使用动态库获取结构中成员的地址
- mongodb - 获取在 MongoDB 中创建文档的月份名称
- vue.js - 使用 Promise 在执行另一项任务之前完成一项任务
- java - 如果 Java 应用程序在关闭时被隐藏,当您单击以重新打开它时会发生什么?
- python - jsonschema 通过具有不同名称或类型的键进行验证