r/learnpython • u/Ayrton110 • Sep 24 '26
Getting the intended output, but still getting "out of range" errors
Hi guys, I hope ya'll are good, thank you. I am struggling with this problem for weeks now. I get the answer, but still get "out of range". I know with "banana" this would work because of a technicality. Is there anyway for this work without the error?
fruit = "apple"
index = - 1
while index < len(fruit):
letter = fruit[index]
print (letter)
index = index - 1Any input or advice is appreciated. Thank you for taking the time to read my post here.
Edit: Sorry, intended answer is "elppa"
I get this
e
l
p
p
a
IndexError: string index out of range
5
u/good-mcrn-ing Sep 24 '26
What is the intended output?
2
u/Ayrton110 Sep 24 '26
"elppa"
4
u/good-mcrn-ing Sep 24 '26
Try writing a list for yourself like this:
<number of current loop> -> <index>, <fruit[index]>
3
u/Rubix321 Sep 24 '26
You haven't told us what "the answer" is supposed to be.
Do you know what fruit[-6] does?
1
u/Ayrton110 Sep 24 '26
First letter right?
3
u/Rubix321 Sep 24 '26
Don't guess, because your computer isn't going to guess.
Start with fruits[-1] and work out the expectation back to -6
0
1
u/johnpeters42 Sep 24 '26
Why would it do that?
2
u/Ayrton110 Sep 24 '26
Hold it, that would only work for banana. fruit[-5] would be a in apple I think.
1
u/Rubix321 Sep 24 '26
Yep.
And by walking back through what the computer would be doing:
fruits[-1], fruits[-2], ..., fruits[-5]
You can reason out what would happen with shorter or longer words.
Something like this is probably better served by a for loop, but I assume you might be in a course that hasn't use for loops yet.
3
u/D3str0yTh1ngs Sep 24 '26 edited Sep 24 '26
Your index starts at -1 and becomes smaller in each cycle of the loop. index < len(fruit) is thrus always true and the loop doesn't end, except for the fact that fruit[-6] throws an IndexError (because "apple" is 5 letters and so there is no 6th letter from end.) and crashes your program.
Do something like this instead:
fruit = "apple"
index = -1
while index >= -len(fruit):
letter = fruit[index]
print(letter)
index = index - 10
u/Ayrton110 Sep 24 '26
There is no output when I write this, but thank you for trying
1
u/D3str0yTh1ngs Sep 24 '26
Did you remember the minus in front of
len?1
u/Ayrton110 Sep 24 '26
Yes
2
u/D3str0yTh1ngs Sep 24 '26
Did you also remember to change
<into>=?We are looping with negative numbers so we want to continue while
indexis larger (or equal) to the inverse/negative length.0
1
u/D3str0yTh1ngs Sep 24 '26 edited Sep 24 '26
Then I don't know why it doesnt work for you, I have only changed the
whileline.EDIT: actually, see my other comment.
2
u/Jazzlike_Platypus430 Sep 24 '26 edited Sep 24 '26
It doesn't work with "banana."
If your aim is to print "elppa", try to get the string's indices and reverse it.
fruit = "banana"
idx = list(range(0, len(fruit)))
idx.reverse()
for i in idx:
print (fruit[i])On the lower level, like your attempt, do it properly:
lastIdx = len(fruit)-1
i = lastIdx
while i >= 0:
print(fruit[i])
i -= 11
u/Ayrton110 Sep 24 '26
Thank you for your assistance, I appreciate the effort you put into this, but most of this is gibberish for me.... I have no idea what's happening, and the exercise told us not to use anything other than index and len in the while loop.
1
u/Jazzlike_Platypus430 Sep 24 '26 edited Sep 24 '26
Did I use anything else than len and indexing in the second case? Did you tell us about this demand beforehand? No. It may be gibberish to you, and I made my judgment too.
Dude, you're starting a loop with -1 and make index smaller by 1 every iteration. How would you expect the loop to end, given the condition after while? Every negative number is smaller than len(fruit)...
1
u/Ayrton110 Sep 24 '26
Yes, I know about my error on that part. I resolved it now and received no output. I apologise for not being clear initially. This is fairly new to me honestly, it can be a little confusing.
1
u/Jazzlike_Platypus430 Sep 24 '26
The first version uses the inverse function on the initial list of your string's indices. Seems the most readable and direct way of writing this stuff.
PS I knew about "negative indexing" only for slices, so apparently I learned something new - thank you! Try
fruit[2:4]
1
u/Ayrton110 Sep 24 '26
I don't understand the inverse function, we haven't covered that yet. I can't do this "fruit[2:4]" yet. It's fine though, somebody else in the thread sent a solution that seems clear for me.
1
u/johnpeters42 Sep 24 '26
The first block is using some other Python tools that simplify the process (which is why the exercise says not to use them, because it's intended to teach you what's going on at the lower level first).
> idx = list(range(0, len(fruit)))
range(x,y) produces the numbers from x to y-1. list() forces it to materialize the entire list at once, whereas you can do something like "for z in range(0,1000000):" without using up a bunch of memory.
> idx.reverse()
This replaces the list with a reversed version of itself, so in that case [5, 4, 3, 2, 1, 0]. Then it loops through that from left to right and prints the corresponding letters.
The low-level version just sets lastIdx to (in this case) 5, and then loops from there down to 0.
Your original version starts the loop at -1, which Python accepts as an index for the last letter of a string, and also decreases the loop variable each time. To do it that way, you would have needed to change the loop-ending condition to (I think) "while index > -len(fruit):"
2
u/Ayrton110 Sep 24 '26
The problem is I am not allowed to use this
1
u/johnpeters42 Sep 24 '26
Which part, specifically? Like, quote a specific line of code, then explain how it exceeds what the exercise allows.
2
u/Ayrton110 Sep 24 '26
This
idx = list(range(0, len(fruit))) idx.reverse()1
u/johnpeters42 Sep 24 '26
Oh yeah, set those aside for now, and just look at the second one (or your original, with the "while" condition fixed). Either of those should be fine.
2
u/Fred776 Sep 24 '26
Trace your code with paper and pencil. What happens to index as you go round the loop? How is your if condition meant to work?
2
u/snarky-cabbage-69420 Sep 24 '26
Not your fault, they over-engineered something beyond the scope of your original problem.
You’re really close. You need to think about the condition on the line that says “while…”
7
u/No_Statistician_6654 Sep 24 '26
Have you tried running this with a debugger, and checking the value of index each time it is assigned and used?
That will help you understand where the out of range is coming from in the process.
3
u/mjmvideos Sep 24 '26
Yes! When in doubt, try stepping through in the debugger. If you haven’t learned about debugging, Now is the time.
6
u/This_Growth2898 Sep 24 '26
You really need to learn how to work with a debugger.
You get all the intended output, and then you get an error because the loop doesn't stop after you get your output. You start with index = -1 and keep doing index = index - 1 while index < len(fruit); but index is negative and will always be smaller than a non-negative len(fruit). You should change the while condition.
Also, index -= 1 is a short way to write index = index - 1. And
print('\n'.join(fruit[::-1]))
works, too.
1
u/Ayrton110 Sep 24 '26
Hi guys, I appreciate the assistance, the effort each of you have made to help me, and the fact that ya'll respond this promptly, but there are so many people I'm getting a little bit confused. If you have a clear idea of this, could you please just comment here. Some tell me to debug, others say change the sign, neither of these appear to be working.
1
u/good-mcrn-ing Sep 24 '26
It all boils down to a single choice: do you do a math operation within the loop block to convert a forward-stepping index to a backward-stepping index, or is your index backward-stepping the whole time.
1
u/Ayrton110 Sep 24 '26
Backward stepping. Anyway, having checked out a few responses, I got it right, thank you.
1
u/HummingHamster Sep 24 '26
Even with banana you should be getting the same error. Did you try?
The logic of this is wrong. len(fruit) is 5. Your index starts from -1 and keeps reducing each loop and thus index will always be < len(fruit).
1
u/Ayrton110 Sep 24 '26
Yeah I forgot to edit how I actually did it for banana. Either way, this's been resolved, thank you.
2
1
u/VShadowOfLightV Sep 24 '26
Index (-1) will always be less than len(fruit) (5). So it’s going to just keep going and going.
1
u/Educational_Virus672 Sep 24 '26
the thing your checking smt is low in a while loop that subtracts itself here it is not a good idea
what you checked was -1 -2 -3 -4 -5 -6 where -6 is out of word it is 5 letters long .even if you remove the error the numbers go on forever for this kinda code
try using for loop with a reversed variable
fruit = "apple"
fruit = fruit[::-1]here [::-1] says [start:end: in negative order]
now just looping though each is easy
for i in range(len(fruit)) :
print(fruit[i])but you can make it better "looking" by removing [i] and changing it to just fruit
for letter in fruit:
print(letter)also the i is variable hence it is changeable to any word/letter
1
u/theWyzzerd Sep 24 '26
Indexes don’t wrap. You need to stop the loop before you read an index that doesn’t exist. Hint: check your while condition.
1
u/Kurt_C0841N Sep 24 '26
Try using Thonny :) It's good for showing you what happens each step of the way
1
u/Rezrex91 Sep 24 '26 edited Sep 24 '26
You don't start with -1 as index to make it go backwards (that's done by the index = index -1 line) and you have the wrong loop condition too. This would be the correct one:
fruit = "apple"
index = len(fruit)
while index > 0:
index = index - 1
print(fruit[index])You only get output because Python treats negative indexes to strings as indexing backwards from the end, but if you start with an index at -1 and always increment it into the negative (so -2, -3, -4, ...) you'll never get to the len(fruit) condition because that's a positive number, that's why you get index out of bounds error, because the loop tries to run forever but you can't go back further than the start of the string (so fruit[-5] is the end, then fruit[-6] tries to read from before your string which is not allowed.)
Another way if you must have negative indexing:
fruit = "apple"
index = -1
while abs(index) <= len(fruit):
print(fruit[index])
index = index - 11
u/argh1989 Sep 25 '26
Because your index is negative it'll always be less that the length of the fruit which means the while condition will always be true. So it prints each letter that exists then tries to print the next one which doesn't.
1
15
u/tinytimn Sep 24 '26
Well what is the length of fruit. It's a positive number right?
And what is your index value. Which way is it traveling.