質問

I want the user to input 10 unique integers in the set [1, 100]. This is my code so far:

user_list = []
print "\nChoose any 10 discrete integers in the set [1, 100]. Do not choose duplicates."

i = 1

while i < 11:
    try:
        number_choice = int(raw_input("\nNumber %d?\n> " % i))

        if (0 <= number_choice <= 100) and isinstance(number_choice, int):
            i += 1
            user_list.append(number_choice)
            print "Your list so far: %r" % user_list
        elif (number_choice < 0) or (number_choice > 100):
            print "'I said to keep it in the set [1, 100].'"
            pass
        else:
            pass

    except ValueError:
        print "'That isn't a discrete integer, is it?'"

print sorted(user_list)

To prevent duplicates, I wanted to change the first if to read:

if (0 <= number_choice <= 100) and (isinstance(number_choice, int)) and (number_choice not in user_list):

This would work, except it would just repeat the "Number %d?" % i prompt again if the user input a duplicate. How can I modify this code so it first displays a prompt 'I said no duplicates.' and then resumes the loop?

役に立ちましたか?

解決

Before the i += 1 line:

if number_choice in user_list:
    print 'No duplicates!'
    continue

他のヒント

Check for duplication first in the if statement, then check for valid integer and add it to the list in the "if else".

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top