15,999,481 members
1.00/5 (1 vote)
See more:
I am gettingstring index out of range on python. I need to get the input in binary.

Input:
1110
Output:
0
If the string has 10 or 11 then the len decreases by 2.
My code gives me index out of range error
But passes for
00 and 010 input.
Fails for 1110

Input:
010
Output:
1

What I have tried:

Python
```n=int(input())
L=len(n)
i=0
While(i```
Posted
Updated 6-Mar-22 4:38am
v2
Richard MacCutchan 6-Mar-22 3:28am
You cannot get the length of an integer, especially as leading zeroes will be lost. You should read the input as a string.
Patrice T 6-Mar-22 10:37am
Your code is incomplete.
Use Improve question to update your question.

## Solution 1

Your code is unreadable: when you paste code, you need to use the "Paste as" option "Code Block", or use the `code`widget on the toolbar above the text box. That tells the system that < and > characters are part of your code and shouldn't be interpreted as HTML:
While(i<L)will be truncated at the < character as it encloses HTML tags in browsers - as can be seen in yoru code.
Enclosed, it looks like this:
Python
```n=int(input())
L=len(n)
i=0
while(i<L)
print("ABCD"[i])
...```
Which is a lot more readable!

To fix your problem, we have to guess what you wrote, but it's probably a simple beginner mistake:
If you have a string of 4 characters, then it's `len` is 4
But the valid indexes start from zero:
`0, 1, 2, 3`
So if your loop runs from to to len inclusive you are trying to access a character that doesn't exist, and you get an error.
Reduce the limit by one to `L - 1` and the error will go away.

But ... why are you converting the input to a integer, then trying to get the length of it anyway?

v2