Python is 0-indexed. Therefore the maximum index of a string is the length of the string minus one. Your loop goes all the way to length, thus going out of range. This is one reason to avoid looping over indexes. Loop directly over the string: for letter in nom: if letter char. Also, you should use more descriptive variable names.
I'm mostly a Java user, however for my GCSE I have to use Python.I was mucking around making an algorithm to find palindromic numbers.The code is a big mess, as I.One- haven't yet entirely figured out Python syntax. And.Two- Haven't shortened the algorithm, except making it start from the higher number and work backwards.The code is as following for python 3.4.1: print('This program will find the nearest palindromic number to a given value.' )countN = input('Input a number above 0 to find the nearest palindromic number')countN = str(countN)nl = len(countN) # Number lengthpf = 0 # Palindrome foundwhile(pf 0 and int(countN)=0): #While no palindrome found and count is bigger than 0ep = nl # end pointersp = -1 # start pointerwhile(int(ep) = sp):if(int(countNep) int(countNsp)):ep = ep-1sp = sp+1print(count + ' is a palindrome.'
)pf = 1else:print(count + ' is not a palindrome.' )countN = countN - 1I was just thinking the changing the pointers bit, should it be separate from the IF statement?Anyway the error I am running into is as follows: This program will find the nearest palindromic number to a given value.Input a number above 0 to find the nearest palindroic number99Traceback (most recent call last):File 'C:/Python34/Computer science/palindrome finder.py', line 10, in if(int(countNep) int(countNsp)):IndexError: string index out of rangePlease note: I have searched here for an answer, part of the reason there are str and int's everywhere.
Your problem is here nl = len(countN) # this is the length of your stringThen you say ep = nl.int(countNep.If you have a string of length 10, the valid indexes are 0 to 9, so 10 is out of range.The quickest fix would be to change your initializations outside the while loop to. Ep = nl -1sp = 0However, to solve such a problem I would just do def isPalindrome(x):text = str(x) # Convert number to stringreturn text text::-1 # Compare string to reversed string isPalindrome(123454321)True isPalindrome(12345)False.
I am piece meal working through the reverse word exercise. I am starting with just breaking down the string and counting the characters in each string and printing each of those characters.(You will see #greyed out code for the next steps).
However, I keep getting one error that I do not know how to correct: IndexError: string index out of rangeThe ranges are quite important because they determine the placement of the letters in the next step.The code is here: script.pydef printletters(string):count = 0newstring = while count.