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

标签 python python-2.7 while-loop try-except

我希望用户在集合 [1, 100] 中输入 10 个唯一的整数。到目前为止,这是我的代码:

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)

为了防止重复,我想将第一个 if 改为:

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

这会起作用,除了它只会重复 "Number %d?"% i 如果用户输入重复则再次提示。我如何修改此代码,使其首先显示提示符 'I said no duplicates.' 然后恢复循环?

最佳答案

i += 1 行之前:

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

关于Python 在用户生成的整数列表、While 循环和 Try-Except 中防止重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23318534/

相关文章:

Python-需要将控制台输出重定向到日志文件

python - 名称错误 : name "webdriver" is not defined

python - 循环直到每个元素返回 true

c# - 为复选框使用 "if"语句的替代方案

python - 使用存储在另一个数据帧中的索引引用数据帧

python - 我可以在 Django 的登录过程中使用外部数据库表吗?

python - 在 AWS 上使用 starcluster 和 ipython 进行集群计算

python - 使用 python 合并两个电子表格 - 新工作表中的列源在源文件之间交替

将字母 append 到文件末尾的 C 程序

python - 带数学运算符的递归函数