I have had an issue where I can’t get the While loop to terminate.
userinput = ("")
while userinput != ("Search" or "Add"):
userinput = input("Search or Add?")
if userinput == "Search":
Search()
elif userinput == "Add":
print("run add request")
else: print("please choose from the following two options.")
Edit: I am sorry the changes have worked. I think after I implemented the changes I had an issue with the Shell running the previous version. Sometimes I have no idea what is happening. Thank you all again.
Edit Edit: Placed the original code back in as I did not take into account that it would confuse anyone looking for their own solution. I am quite new in terms of usage of the site. Thanks again for the help
>Solution :
The issue is with your while test. A couple of things:
-
You can’t use
orlike this.orneeds two full conditions that resolve totrueorfalse. Here you have one conditionuserinput != "Search"and a string"Add". So it’s always going to returnTruesince a non-zero value is alwaysTrue.As an example:
if "Add": print("true") >>trueInstead:
userinput != "Search" or userinput != "Add" -
oris not correct when testing two negations like!=. One of the two conditions will always returntrue. For instance if you input"Add"then the conditionuserinput != "Search"will beTrueand yourwhileloop will continue sinceTrue or False = True. So on and so forth. Instead you want anand.while userinput != "Search" and userinput != "Add":
As I suggested in my comment though, it’s probably just easier to use the not in operator on a list:
while userinput not in ['Search','Add']:
This way as your list grows your test stays nice and small/condense.
Also, while this is just my opinion, I applaud your original pre-edit code where you supplied the condition for breaking your while loop in the while statement instead of doing while True:. Having had many years of bug hunting and feature adding and hotfixing, I know every time I see while True: I’m going to be hunting through hundreds of lines of codes looking for every break. while True: and break has its time and place (I imagine), but I feel like it should be an exception use-case, not the rule.