我要求用户输入一个由4个数字组成的列表,并且我必须验证它们是否都不同(如果不是,他必须再做一次),但这是一项较大的作业,我只能使用简单/基本的代码,这意味着我不能使用集合或任何函数,只能使用列表,循环...
因此,我要求用户一次输入1个元素,以便每次将它们与已经输入的元素进行比较,但是我想这样做的方法要简单得多。我的程序看起来像:
code= input ("enter a list of four distinct numbers between 1 and 8:")
for c in code:
while type (code)!=list or len(code)!=4 or type(c)!=int or code[c]<1 or code[c]>8 or ????????? :
print "try again ! this is not correct"
code=input("enter a list:")
我怎样才能做到这一点 ?谢谢
这是一个解决方案,他们一次输入一个值,如果不符合您的条件,则提示您重新输入。
values = [] # initialize empty list
while len(values < 4):
value = int(input("enter a number between 1 and 8:"))
if value in values: # Check if unique
print("You already entered this")
elif value < 1 or value > 8: # Check bounds
print("Value must be between 1 and 8")
else:
values.append(value) # Valid number, add to your list
print(values) # print out the final list
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句