I am having issues trying to get a while loop to validate the users input, and then make sure the user doesn’t repeat values. Shown bellow are the two methods I have tried, but I can’t get my head around how to get them to work.
Method 1
def test():
my_list = ["", "", ""]
for i in range(3):
while (my_list[i] != "one") and \
(my_list[i] != "two") and \
(my_list[i] != "three"):
while (my_list[i] == my_list[0]) and \
(my_list[i] == my_list[1]) and \
(my_list[i] == my_list[2]):
text = "Enter, one, two or three", i + 1, ":"
try:
my_list[i] = input(text)
except KeyboardInterrupt:
sys.exit()
print(my_list)
Method 2
def test2():
my_list= ["", "", ""]
while len(my_list)!=len(set(my_list)) == True:
for c in range(4):
while (my_list[i] != "one") and \
(my_list[i] != "two") and \
(my_list[i] != "three"):
text = "Enter, one, two or three", c + 1, ":"
try:
my_list[c] = input(text)
except KeyboardInterrupt:
sys.exit()
print(my_list)
Why not simplify it a bit:
This is a more-or-less direct translation of your requirements:
Using
for x in range(y)in this case just adds complexity, because you don’t actually know how many times you want the loop to run.There’s no reason to pre-fill the list with invalid values (
my_list = ["", "", ""]), since lists can be resized withappend.Also, your
sys.exitcode is unnecessary and probably harmful. Just let the exception propagate and it will crash the program itself (unless you catch it, which you shouldn’t almost never do for aKeyboardInterruptexception).Note: Your first version would work if you combined the two while loops into one, it’s just unnecessarily complicated.