简体   繁体   English

Python防止用户生成的整数列表,While循环和Try-Except中的重复项

[英]Python Preventing Duplicates in User-Generated Integer List, While-loop and Try-Except

I want the user to input 10 unique integers in the set [1, 100]. 我希望用户在集合[1,100]中输入10个唯一整数。 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阅读:

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 这会起作用,只不过会重复"Number %d?" % i "Number %d?" % i prompt again if the user input a duplicate. 如果用户输入重复项, "Number %d?" % i再次提示。 How can I modify this code so it first displays a prompt 'I said no duplicates.' 如何修改此代码,使其首先显示提示'I said no duplicates.' and then resumes the loop? 然后恢复循环?

Before the i += 1 line: i += 1行之前:

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

首先在if语句中检查重复项,然后检查有效的整数并将其添加到“ if else”中的列表中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM