我希望用户在集合 [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/