I have below python
code as you can see I am taking names as an input from user and if it matches with the name that is present in names list then code breaks. My current requirement is if user types numbers (ex: 1,2 ) or names (Left,right) other then mentioned in list then it should prompt them with error "Incorrect entry. Please type names from below list" and should print the list elements in rows. The issue with below code is it is printing the elements list based on length of list elements. For example. If I type "Left","Right", "center" as input then my below code is printing the output as shown in Output section instead of printing the output shown in expected output .
My question is how to fix below code such that when user types incorrect names separated by comma then it should print list element once. I am sure I might be missing minor thing but not sure what it is ?
Note: The reason I am using filter in the input section of the code is because I want to remove empty elements from the list that is getting generated by user input.
Thanks in advance for your time!
Code
names=['test','bob','rob']
def validate1(string_text):
try:
for x in string_text:
if x not in names:
print("Incorrect entry please enter names from below list")
for y in names: print(y)
else:
return True
except ValueError:
print("Incorrect entry. Please enter name in string format ONLY!")
return False
while True:
name_with_deg=list(filter(None,input("Enter names separated by (,):").split(",")))
if validate1(name_with_deg):
break
Output:
Enter names separated by (,):Left,Right,center
Incorrect entry please enter names from below list
test
bob
rob
Incorrect entry please enter names from below list
test
bob
rob
Incorrect entry please enter names from below list
test
bob
rob
Expected Output:
Enter names separated by (,):Left,Right,center
Incorrect entry please enter names from below list
test
bob
rob
CodePudding user response:
The for x in string_text:
loops over each name, so multiple names/multiple loops doing testing. What you want is to test that all the names are in names
in one test. Here's a way using all
and a generator expression:
names=['test','bob','rob']
def validate1(name_list):
result = all(name in names for name in name_list)
if not result:
print('Incorrect entry please enter names from below list')
for name in names:
print(name)
return result
while True:
# list(filter(None,...)) didn't do anything...removed.
# input() always returns a string, so the try/except wasn't needed either
name_with_deg = input('Enter names separated by (,):').split(',')
if validate1(name_with_deg):
break