I am trying to check if a user input as a string exists in a list called categoriesList which appends categories from a text file named categories.txt. If the user inputs a category that then exists in categoriesList my code should be able to print out "Category exists", otherwise "Category doesn't exist".
Here is the code:
categoriesList = []
with open("categories.txt", "r") as OpenCategories:
for category in (OpenCategories):
categoriesList.append(category)
while True:
inputCategories = input("Please enter a category:")
if inputCategories in categoriesList:
print("Category exists")
break
else:
print("Category doesn't exist")
break
When I run this code it always outputs Category doesn't exist even if the category I enter actually exists in categoriesList. How would I solve this problem in the code? Furthermore, I want to be able to get one input from the user for entering a category so I don't want "Please enter a category" to come up several times, I just want the code to make it come up just once.
Also, it would be much appreciated if I could know the code on how I would then do all of the above in tkinter as I need to do the above in GUI. I think you need to have labels and allow the user to enter a category in a box on the screen.
CodePudding user response:
When you read from a textfile you also read special characters such as '\n' therefore this must be removed. This can be done as shown in the code below.
I also slightly tweaked you loop layout as you don't want to have the while loop inside the for loop - otherwise you would be searching the list before all categories had been added.
categoriesList = []
with open("categories.txt", "r") as OpenCategories:
for category in (OpenCategories):
categoriesList.append(category.strip()) #remove newline, tabs etc
while True:
inputCategories = input("Please enter a category:")
if inputCategories in categoriesList:
print("Category exists")
break
else:
print("Category doesn't exist")
break
You may also want to remove any spaces ' ' from your category list. This could be done by replacing
category.strip()
with
category.strip().replace(' ','')
You may also want to make the inputted variable and the category all lowercase for easier comparison. This can be done using the lower function on the string.
e.g. inputCategories = inputCategories.lower()
CodePudding user response:
The while loop should not be inside the for loop and the while loop is not necessary at all:
with open("categories.txt", "r") as OpenCategories:
categoriesList = OpenCategories.read().splitlines()
# don't need the while loop
inputCategories = input("Please enter a category:")
if inputCategories in categoriesList:
print("Category exists")
else:
print("Category doesn't exist")
