Home > database >  How not to start entering again list when there is an error
How not to start entering again list when there is an error

Time:10-16

I have code where the user fills the list with elements, but there are two conditions (the elements must not be empty " " and duplicated). How can I make it so that when the user enters an empty or duplicate element, user does not have to enter all the elements of the list again, but only the one where the error occurred

first = []  

n = int (input ("Enter the number of elements of the first list (elements are not duplicated!): ")) 
for i in range(n):
    print("""Enter element of the list: """)  
    element = (input())
    if element == "":
        element = input("""and entered an empty element, try again 
""")     
    first.append(element)
    for i in range(len(first)):
        if first.count(first[i]) > 1:
            print("You duplicated an element")

print(first)

THANKS!

CodePudding user response:

I think what you are looking for is a while loop (or recursion, but we will stick to a while loop for now). To identify duplicates we will store any new element in a set. This means that when we receive a new input, we just check if it is already in the set or not. Here is some example code. Good luck!


result = []  
stored_inputs = set()
n = int (input ("Enter the number of elements of the first list (elements are not duplicated!): ")) 

for i in range(n):
    while True:
        element = input("Enter element")
        
        if element == "":
            print("empty elements not allowed")
            continue
    
        if element in stored_inputs:
            print("duplicate elements not allowed")
            continue
    
        stored_inputs.add(element)
        result.append(element)
        break


CodePudding user response:

just separate your input logic from your error checking logic:

def check_valid(input_item,input_list):  # function to validate input
    if input_item == "":
        print("entered an empty element, try again")
        return False
    elif input_item in input_list:
        print("You duplicated an element, try again")
        return False
    return True:

first = []  

n = int (input ("Enter the number of elements of the first list (elements are not duplicated!): ")) 
for i in range(n):  # actual input logic
    print("Enter element of the list: ")
    element = input()
    while not check_valid(element,first):
        element = input()
    first.append(element)

print(first)

one advantage of this is that your error checking logic is easily extendable to more error cases.

  • Related