#python #loops #while-loop
Вопрос:
я новичок, и я начал изучать python , мне нужно достичь нижеприведенной цели, остановить цикл while, если он столкнется с ошибкой, такой как индекс вне диапазона.
что-то не так :ошибка индекса: строковый индекс вне диапазона.
вот приведенный ниже код: не могли бы вы мне помочь, ребята ?
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("********************")
Комментарии:
1. У вас есть
st[i]
состояние в то время как, которое выполняется сразу послеi = i 1
в цикле. Это означает, что вы ничего не делаетеi
, чтобы предотвратить выход за пределы досягаемости. Вы должны спроектировать свой цикл так, чтобы он никогда не пытался получить доступ к каким-либо значениям после конца списка.2.
while st[i] != '.' or len(st) >= 1:
может выполняться «вечно» (до тех пор, пока вы не получите ошибку), если». » отсутствуетst
иst
не пусто.3.
while i < len(st) and st[i] != '.':
4. привет, попробовал ниже : ‘в то время как st[i] != ‘.’ и k != «» и я
Ответ №1:
Если вы хотите остановить цикл без завершения процедуры (т. Е. Достичь «возврата»), просто оберните это «пока» в try: … кроме блока
Комментарии:
1. Пожалуйста, добавьте дополнительные сведения, чтобы расширить свой ответ, например, ссылки на рабочий код или документацию.
2. я не могу использовать блок «кроме»… это действительно решение…:>
Ответ №2:
мне удалось ответить на свой собственный вопрос!!! да!!! вот код:
i = 0
count = 0
k = st
z = len(st)
while st[i] != '.' and k != " ":
if st[i] in 'aeiou':
count = count 1
i = i 1
if i >= z:
break
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("********************")
»’
»’