如果输入的积分不在0、20、40、60、80、100和120范围内,程序应显示"Out of range&qu



为了解决上面的问题,我尝试创建一个包含范围的列表,然后创建一个包含其中变量的列表。然后检查变量是否在列表中,我使用了if循环,但是它不工作,只打印出"超出范围……"。我也尝试了一个while循环,它只会重复总共7次。我不知道如何解决它,并希望得到一个答案。谢谢你

def main():
a = [0, 20, 40, 60, 80, 100, 120]
try:
userPass = int(input("Enter pass credits: "))
userDefer = int(input("Enter defer credits: "))
userFail = int(input("Enter fail credits: "))
except:
print("Invalid number.")
total = userFail + userPass + userDefer
aValues = [ userPass, userFail, userDefer ]
if aValues in a:
print(total)
else:
print("Out of range. Try again")
if total > 120:
print("Total incorrect")
repeat()
else:
if userPass >= 120:
print("This student has progressed.")
repeat()
elif userPass >= 100 and total == 120:
print("This student is trailing.")
repeat()
elif userFail <= 60 and total == 120:
print("This student did not progress(module retreiver).")
repeat()
elif userPass <= userFail:
print("This students program outcome is exclude.")
repeat()
else:
print("incorrect. Try again.")
repeat()

def repeat():
choice = int(input("If you would like to quit type 1 or test another student write 2: "))
if choice != 1 and choice != 2:
repeat()
else:
while choice == 2:
main()
while choice == 1:
break
print("Thank you.")
main()

测试一组数字是否在另一组中是一个集合操作。所以用set减去输入的所有有效值。

a = set([0, 20, 40, 60, 80, 100, 120])
if set([userPass, userFail, userDefer]) - a:
print("Out of range. Try again")

有趣的是,您还可以使用range对象。它的构建是为了有效地检查容器
a = range(0, 121, 20)
if any(val in a, for val not in (userPass, userFail, userDefer)):
print("Out of range. Try again")

你需要改变第一个if

if aValues[0] in a and aValues[1] in a and aValues[2] in a :
print(total)

如果你需要添加更多的值,你可以这样做:

total=0
for i in range(len(aValues)):
if(aValues[i] in a):
total=total+ aValues[i]
else:
print('Incorrect Value')
print(total)

相关内容

最新更新