how to reject duplicate values

441 views Asked by At

I'm making a program whereby the user has two enter 10 integers:

a = input('Enter an integer: ')
b = input('Enter an integer: ')
c = input('Enter an integer: ')
d = input('Enter an integer: ')
e = input('Enter an integer: ')
f = input('Enter an integer: ')
g = input('Enter an integer: ')
h = input('Enter an integer: ')
i = input('Enter an integer: ')
j = input('Enter an integer: ')

I would like to know how to reject a number which has already been entered already and then prompt the user to enter another value

2

There are 2 answers

2
Kevin On BEST ANSWER

Store your numbers in a collection, such as a list. Then you can check if new numbers are already in the collection before adding more.

integers = []
while len(integers) < 10:
    a = input("Enter an integer: ")
    if a in integers:
        print("Sorry, that number was already entered.")
    else:
        integers.append(a)

If you don't care about the order of the integers, you can use a set, which imposes uniqueness automatically.

integers = set()
while len(integers) < 10:
    integers.add(input("Enter an integer: "))
0
Alex Ivanov On
#!/usr/bin/python

integers=[]

def check(a):
    while a in integers:
        print a, 'exists.'
        a = input('Enter another integer: ')
    integers.append(a)


a = input('Enter an integer: ')
check(a)

b = input('Enter an integer: ')
check(b)

c = input('Enter an integer: ')
check(c)

d = input('Enter an integer: ')
check(d)

e = input('Enter an integer: ')
check(e)

f = input('Enter an integer: ')
check(f)

g = input('Enter an integer: ')
check(g)

h = input('Enter an integer: ')
check(h)

i = input('Enter an integer: ')
check(i)

j = input('Enter an integer: ')
check(j)

Or a shorter version for 10 integers

#!/usr/bin/python

integers=[]

def check(a):
    while a in integers:
        print a, 'exists.'
        a = input('Enter another integer: ')
    integers.append(a)

while len(integers)<10:
    a = input('Enter an integer: ')
    check(a)