Python实现列表单词是否以元音开头的判断问题求解
代码修复方案与实现
原代码问题点
- 循环逻辑错误:
for month in range(len(year))获取的是列表索引的数值,不是月份字符串,无法调用字符串方法startswith - 输出逻辑错误:
print语句放在循环外,只会输出最后一次的判断结果,同时使用了未定义的变量i - 语法错误:
print语句末尾缺少闭合右括号
正确实现代码
# 定义月份列表和元音前缀元组 year = ["january","february","march","april","may","june","july","august","september","october","november","december"] vowels = ("a", "e", "i", "o", "u") # 遍历每个月份直接判断 for month in year: if_vowel = "Yes" if month.startswith(vowels) else "No" print("Does the month of {0} start with a vowel? {1}".format(month, if_vowel))
代码利用了Python内置的str.startswith()支持传入元组匹配任意前缀的特性,直接判断月份是否以元音开头,每次循环完成判断后立刻输出对应结果,覆盖所有月份的校验需求。
部分输出示例
Does the month of january start with a vowel? No
Does the month of april start with a vowel? Yes
Does the month of august start with a vowel? Yes
Does the month of october start with a vowel? Yes
内容的提问来源于stack exchange,提问作者HelloWorld
相关产品推荐
相关产品推荐

