how to reject duplicate values

时间:2015-06-15 15:13:38

标签: python duplicates prompt

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 个答案:

答案 0 :(得分:2)

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: "))

答案 1 :(得分:-1)

#!/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)

或10个整数的较短版本

#!/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)