Python新手while循环报IndexError字符串索引越界问题求修复
问题排查
你遇到的IndexError由两个核心问题导致:
- while循环条件逻辑错误+执行顺序错误
原有条件st[i] != '.' or len(st) >= 1存在两个问题:- 优先访问
st[i]再判断长度,只要i超过字符串最大索引,访问st[i]就会直接触发越界错误 - 逻辑运算符用错
or,只要任意一个条件成立循环就会继续,哪怕i已经越界,只要字符串长度≥1就会一直执行
- 优先访问
- 代码缩进不规范,Python依赖缩进区分代码块,原有函数内代码、测试用例的if判断缩进全部错乱,会先触发语法错误。
修正后完整代码
def mystery(st): ## Modify anything you want in this function: i = 0 count = 0 # 先判断索引合法性,再判断当前字符不是句号,两个条件同时满足才继续循环 while i < len(st) and st[i] != '.': if st[i] in 'aeiou': count = count + 1 i = i + 1 return count ### TESTS ### print("********************") print("Starting the test:") print("********************") print("Checking 'hello. world.'") ans = mystery('hello. world.') if ans == 2: print("CORRECT: 'hello. world.' has 2 vowels before the first period") else: print("WRONG: 'hello. world.' has 2 vowels before the first period but the code returned", ans) print("********************") print("Checking 'hello world. nice to meet you.'") ans = mystery('hello world. nice to meet you.') if ans == 3: print("CORRECT: 'hello world. nice to meet you.' has 3 vowels before the first period") else: print("WRONG: 'hello world. nice to meet you.' has 3 vowels before the first period but the code returned", ans) print("********************") print("Checking ' '") ans = mystery(' ') if ans == 0: print("CORRECT: The string ' ' has no vowels") else: print("WRONG: The string ' ' has no vowels but the code returned", ans) print("********************") print("Checking 'dddda'") ans = mystery('dddda') if ans == 1: print("CORRECT: 'dddda' has 1 vowel") else: print("WRONG: 'dddda' has 1 vowel but the code returned", ans) print("********************") print("Tests concluded, add more tests of your own below!") print("********************")
关键修改说明
- 利用Python的短路求值特性,把
i < len(st)放在循环条件最前面,只要i超出合法索引范围,就不会再执行后面的st[i]访问,直接终止循环,避免索引越界 - 把逻辑运算符换成
and,只有索引合法且没遇到句号的时候才会继续遍历,符合需求:统计字符串中第一个句号之前的元音数量,没有句号就统计整个字符串的元音数量 - 修正了所有代码的缩进错误,确保可以正常运行
内容的提问来源于stack exchange,提问作者user3088460
相关产品推荐
相关产品推荐

