Python:如何迭代嵌套在while循环中的列表



我有以下代码:

shape = input("Please enter your choice of shape? ")    
nthTime = ["second","third","fourth","fifth","sixth"]
while shape.lower() not in ["octagon","heptagon","hexagon"] :
    print("Please select a shape from the list!")
    shape = input("Pick a shape, for the " + nthTime + " time! ")

我如何才能实现这样的结果,Python每次通过while循环时都会迭代列表"nthTime"?

我可以使用嵌套的for循环,但这当然会运行整个列表,这不是我的目标。

因此,我得出结论,我需要使用嵌套的while循环;但是我搞不清楚确切的语法。

我希望这个问题将来也能对其他人有用。

只有当用户输入正确的值时,才使用for循环并中断循环

for iteration in nthTime:
    if shape.lower() not in ["octagon","heptagon","hexagon"]:
        print("Please select a shape from the list!")
        shape = input("Pick a shape, for the " + iteration + " time! ")
    else: break
else: print "You have wasted all your chances, try again later"

类似这样的东西:

shape = input("Please enter your choice of shape? ")    
nthTime = ["second","third","fourth","fifth","sixth"]
undesired_shapes = ["octagon","heptagon","hexagon"]
indx = 0
while shape.lower() not in undesired_shapes:
    print("Please select a shape from the list!")
    shape = input("Pick a shape, for the " + nthTime[indx] + " time! ")
    indx += 1
    if indx >= len(nthTime):
        print 'Giving up !!'
        break
nthTime.reverse()
while shape.lower() not in ["octagon","heptagon","hexagon"] and nthTime:
    print("Please select a shape from the list!")
    shape = input("Pick a shape, for the " + nthTime.pop() + " time! ")

最新更新