#π Index error dependent on an else statement
19 messages Β· Page 1 of 1 (latest)
@lethal blaze
Remember to:
- Ask your Python question, not if you can ask or if there's an expert who can help.
- Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
- Explain what you expect to happen and what actually happens.
:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.
Print index.
can you paste the code here as text please?
def solution(input):
slist = []
newstring = list(input)
for index in range(0, len(input), 2):
if index == (len(input)-1):
slist.append(input[-1] + "_")
else:
slist.append(input[index] + input[index+1])
return slist
Hey @lethal blaze!
It looks like you're trying to paste code into this channel.
Discord has support for Markdown, which allows you to post code with full syntax highlighting. Please use these whenever you paste code, as this helps improve the legibility and makes it easier for us to help you.
To do this, use the following method:
```py
print('Hello, world!')
```
This will result in the following:
print('Hello, world!')```
You can **edit your original message** to correct your code block.
Basicly, the if is to prevent the line after the else running in a particular circumstance (right at the end). By removing it you run this line which is known to try to access things bey0ond the end of the array.
!e
def solution(input):
slist = []
newstring = list(input)
for index in range(0, len(input), 2):
if index == (len(input)-1):
slist.append(input[-1] + "_")
# else:
# slist.append(input[index] + input[index+1])
return slist
print(solution('asdfadsf'))
:white_check_mark: Your 3.12 eval job has completed with return code 0.
[]
Print index in the loop before the if-statement. Then thinks about what is being accessed when it explodes.
I see no errors with the else commented out
The OP commented out only the else, not the whole clause.
oh you're right, whoops
In both cases it should still access the last even index then try to concat the next index?
The error to me is just odd because the index+1 is specifically considered outside the array and I'm understanding that to always be true whether the else is commented out or not. Since all iterations should pass through it after the if line?
The if is to see: am I right at the end of the array. if so, just access the end item and add an underscore. Otherwise (else) you can access the index and the next index.
This looks like homework, an exercise to make you think about dealing with indices near the end of the array etc.
This help channel has been closed and it's no longer possible to send messages here. If your question wasn't answered, feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.