Swastik Mohapatra Swastik Mohapatra - 3 months ago 10
Python Question

NameError: name "user_choice1" is not defined

I am trying out a simple program and keep getting this particular error:

line 34, in <module>
user_choice1 == input("Do you want to exit or continue searching?")
NameError: name 'user_choice1' is not defined


Here is the piece of code that is causing the error:

while True:
choice = input("Do you want to add items?")
if choice == "y":
add_items()
more = input("Do you want to add more items?")
if more == "y":
add_items()
else:
while True:
user_choice = input("Adding items finished. Do you want to search items or exit?")
if user_choice == "search":
search_item()
while True:
user_choice1 == input("Do you want to exit or continue searching?")
if user_choice1 == "continue":
search_item()
continue
elif user_choice1 == "exit":
sys.exit()
else:
break
elif user_choice == "exit":
sys.exit
else:
continue


elif choice == "n":
search_item()
while True:
user_choice2 = input("Searching finished. Do you want to continue or exit?")
if user_choice2 == "continue":
break
continue
elif user_choice2 == "exit":
sys.exit()
else:
continue

elif choice == "exit":
sys.exit()

else:
print("Invalid Choice")


What is causing this error? I am using Python 3.5.2.
Also, is there a better way to write this code as in, is there a way to optimize this code?

Answer

In Python, using a double-equal, ==, is a logical test of equality. Using a single-equal, = is an assignment.

So what you're doing is telling Python to check whether user_choice1 is equal to the input statement. It's rightly telling you that you haven't defined that variable yet.

x = 4 #assigns the value 4 to x
y = 4 #assigns the value 4 to y
x == y #returns True
x == 7 #returns False

It looks like you repeated this error in several places, so go back and switch to a single equal for all of them.

Comments