[Answered] Getting a ValueError

Hi, i am getting “ValueError: invalid literal for int() with base 10: ‘quit’” when inputting quit to line 5(Enter an index (-1 to quit): ) but i can’t work out why as index is being declared as a string and the if statement is checking for a string and so to me there should be no value error. I am also quite new to programming so don’t expect any spectacular programming from me. Thanks in advance for any help.

initial=input('Enter a word: ')
initial_list=list(initial)
def get_index():
    while True:
        index=str(input('Enter an index (-1 to quit): '))
        if int(index)<(-1) or int(index)>len(initial_list):
            print('Invalid Index')
        elif str(index)=='quit':
            break
        else:
            letter=input('Enter a letter: ')
            initial_list[int(index)]=letter
            print(''.join(initial_list))

get_index()

I am aware that i do not need to declare index as a string using str(), that was simply part of my troubleshooting.

input() always returns a str (so the str() surrounding this is not necessary).

int(index)

This will attempt to take the value in index and turn it into an int. If it can, it returns the value. If it cannot, it will raise a ValueError.

>>> int("345")
345
>>> int("quit")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'quit'

So the if line needs a value for int(index). It doesn’t get one and the conditional is never checked.

Oh i see what you mean, i didn’t think of that as i added the elif statement after i wrote everything else. Wasn’t really paying much attention to things like that. Thanks for the help.