Click here to Skip to main content
15,897,891 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
lst = ["milk", "butter", "bread", "eggs", "water"]
lst1 = []
answ = ""
numb = ["1", "2", "3", "4", "5"]




while answ != "0":
    if answ in "12345":
        index = int(answ) - 1
        char = lst[index]
        lst1.append(char)
        print(f"Your list now contains {lst1}")


AND I KEEP GETTING THIS ERROR :
    index = int(answ) - 1
ValueError: invalid literal for int() with base 10: ''


What I have tried:

I've tried replacing "12345" by ["1", "2", "3", "4", "5"] and it worked well , but i want to know why do i keep getting this error
Posted
Updated 21-Aug-21 5:01am
Comments
Richard MacCutchan 21-Aug-21 9:30am    
You do not have a valid number in the answ variable (it contains nothing). But even if you put a valid number in, your while loop will run for ever. You need to rework that code.

answ never gets changed, so it always contains an empty string. Since an empty string does not contain any valid numeric value, you get an error when you try to convert it to an integer.

Try this:
Python
answ = "1"
And it'll work a little better, but that code is never going to exit or do anything useful!
 
Share this answer
 
Quote:
How do i...solve this error index = int(answ) - 1 valueerror: invalid literal for int() with base 10: ''

Your code do not behave the way you expect, or you don't understand why !

There is an almost universal solution: Run your code on debugger step by step, inspect variables.
The debugger is here to show you what your code is doing and your task is to compare with what it should do.
There is no magic in the debugger, it don't know what your code is supposed to do, it don't find bugs, it just help you to by showing you what is going on. When the code don't do what is expected, you are close to a bug.
To see what your code is doing: Just set a breakpoint and see your code performing, the debugger allow you to execute lines 1 by 1 and to inspect variables as it execute.

Debugger - Wikipedia, the free encyclopedia[^]

Mastering Debugging in Visual Studio 2010 - A Beginner's Guide[^]
Basic Debugging with Visual Studio 2010 - YouTube[^]

27.3. pdb — The Python Debugger — Python 3.6.1 documentation[^]
Debugging in Python | Python Conquers The Universe[^]
pdb – Interactive Debugger - Python Module of the Week[^]

The debugger is here to only show you what your code is doing and your task is to compare with what it should do.
 
Share this answer
 

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