0

I made a code that inserts into a list the amount of numbers that the user wants.

But in the following snippet:

  • Excerpt for alteration
number = int(input("Enter an integer: "))
# If greater than zero, the number is stored
if number >= 0:
   list.append(number)
# If not, the code closes
else:
   print ("Negative numbers are not allowed, ending code...\n")
   break

The improvement I'm thinking about should allow the insertion of non-duplicate numbers, and if this occurs it should enter a condition in which it displays a duplicate number message and returns to the number insertion action. How do I make this change?

  • Code complete
# Create a empty list
list = []
# While the for True loop will always be working
while True:
    try:
        print ("Do you want to insert numbers in the list? (NO = 0 | YES = 1)")
        begin = int(input("Type your answer: "))
        # If the user closes the code without entering numbers, the code ends
        if begin == 0:
            print ("If you do not want to insert numbers in the list, the code will be terminated.\n")
            break
        # If you enter an invalid option, the code ends
        elif begin != 1:
            print (f"Option {begin} invalid, the code will be finalized.\n")
            break
        # If the user wants
        else:
            number = int(input("Enter an integer: "))
            # If greater than zero, the number is stored
            if number >= 0:
                list.append(number)
            # If not, the code closes
            else:
                print ("Negative numbers are not allowed, ending code...\n")
                break
            # Asks if you want to continue entering numbers
            print ("Do you want to continue entering numbers? (NO = 0 | YES = 1)")
            question = int(input("Type your answer: "))
            # If not, the code closes
            if question == 0:
                print ("Finishing code... \n")
                break
            # If the answer is yes, the process of entering numbers begins again
            elif question == 1:
                print ("Good thing you keep inserting the numbers inside the list.")
                print (f"Number of numbers in the list: {len(list)}")
                print (list)
                pass
            # If you enter an invalid option, the code ends
            else:
                print (f"Option {question} invalid, the code will be finalized.\n")
                break
    # If the user enters an invalid option
    except Exception:
        print ("Only positive numbers are allowed, ending code... \n")
        break
# Message
print (f"The number of numbers in the list is {len(list)}.")
print (list)
Kaneshi
  • 3
  • 4
  • 1
    First off, don't call your variable `list`. And maybe break your code into functions. One to validate the input ("Do you want to continue entering numbers") and one to check for duplicates. – not_speshal Mar 09 '22 at 14:12

0 Answers0