You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python元音辅音统计代码语法错误与逻辑异常求助

问题分析与修复方案

原代码存在的问题

  • 缩进错误:函数内的if语句未缩进在for循环块内,导致ascii_value变量作用域异常;while循环内的sentence_list定义、循环逻辑及函数调用,还有choice==2的判断均存在缩进混乱,破坏了代码逻辑层次。
  • 参数传递错误:调用checkVowelsConsonants时,每次添加字符到列表后就传入整个列表,实际无需将字符串转列表,直接传入完整字符串即可(字符串本身支持迭代)。
  • 元音判断冗余:分大小写重复编写元音判断逻辑,代码冗余度高。
  • 打印位置错误:结果打印语句嵌套在else块内,仅在统计辅音时触发打印,无法在循环结束后统一输出最终统计结果。
  • 拼写错误:consonats应为consonants,choioce应为choice,other that应为other than。

修正后的代码

def checkVowelsConsonants(s):
    vowels = 0
    consonants = 0
    for ch in s:
        # 转换为ASCII值
        ascii_value = ord(ch)
        # 判断是否为英文字母
        if (65 <= ascii_value <= 90) or (97 <= ascii_value <= 122):
            # 统一转小写判断元音,简化逻辑
            if ch.lower() in {'a', 'e', 'i', 'o', 'u'}:
                vowels += 1
            else:
                consonants += 1
    # 循环结束后统一打印统计结果
    print(f"The number of vowels is {vowels} and consonants is {consonants}")

while True:
    # 打印功能菜单
    print("1. Print the number of vowels and consonants")
    print("2. Exit the program")
    # 处理用户输入,避免非数字导致崩溃
    try:
        choice = int(input("Enter choice: "))
    except ValueError:
        print("Please enter a valid number!")
        continue
    # 执行统计功能
    if choice == 1:
        sentence = input("Enter a sentence: ")
        checkVowelsConsonants(sentence)
    # 退出程序
    elif choice == 2:
        break
    # 无效选择提示
    else:
        print("Invalid choice!")

额外优化说明

  • 增加输入合法性判断,避免用户输入非数字时程序崩溃。
  • 使用f-string替代字符串拼接,代码更简洁易读。
  • 用集合存储元音字母,替代多个or判断,提升判断效率。

内容的提问来源于stack exchange,提问作者Wasteman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 22:46:02