Click here to Skip to main content
15,884,473 members
Please Sign up or sign in to vote.
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
Comments
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.

1 solution

Your code is unreadable: when you paste code, you need to use the "Paste as" option "Code Block", or use the codewidget 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?
 
Share this answer
 
v2
Comments
Maciej Los 6-Mar-22 9:07am    
5ed!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900