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

Python新手while循环报IndexError字符串索引越界问题求修复

问题排查

你遇到的IndexError由两个核心问题导致:

  1. while循环条件逻辑错误+执行顺序错误
    原有条件st[i] != '.' or len(st) >= 1存在两个问题:
    • 优先访问st[i]再判断长度,只要i超过字符串最大索引,访问st[i]就会直接触发越界错误
    • 逻辑运算符用错or,只要任意一个条件成立循环就会继续,哪怕i已经越界,只要字符串长度≥1就会一直执行
  2. 代码缩进不规范,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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 01:00:04