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

时间:2016-01-02 18:12:10

标签: python while-loop

我有以下代码:

iif

我怎样才能实现结果,Python每次通过`while-loop时都会遍历列表' nthTime'

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

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

我希望将来这对其他人来说也是一个有用的问题。

3 个答案:

答案 0 :(得分:2)

仅当用户输入正确的值

时,才使用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"

答案 1 :(得分:1)

这样的事情:

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

答案 2 :(得分:0)

locale: 'ru'