【发布时间】:2021-09-08 18:05:11
【问题描述】:
我是新手,我开始学习python, 我需要实现以下目标,如果遇到索引超出范围等错误,请停止 while 循环。
出了点问题:IndexError: string index out of range.
这是下面的代码:你们能帮帮我吗?
def mystery(st):
## Modify anything you want in this function:
i = 0
count = 0
while st[i] != '.' or len(st) >= 1:
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("********************")
【问题讨论】:
-
您的 while 条件中有
st[i],它在循环中的i = i + 1之后运行。这意味着您没有采取任何措施来防止i超出范围。您必须设计循环,使其永远不会尝试访问列表末尾之外的任何值。 -
while st[i] != '.' or len(st) >= 1:可以“永远”运行(直到出现错误)如果 '.'不在st中且st不为空。 -
while i < len(st) and st[i] != '.': -
嗨,尝试了以下方法:'while st[i] !='.'和 k != " " 和 i
标签: python loops while-loop