如何在Python的嵌套循环函数中限制循环的迭代次数?

时间:2019-11-26 14:08:23

标签: python function loops nested iteration

如何限制Python嵌套循环函数中循环的迭代次数?

代码:

friends= ['Ali', 'Asma','Amna', 'Izma', 'Omer','Zahid','Bilal','Sarah']
for vowelnames in friends:
    if vowelnames in ('Ali','Asma','Izma','Omer'):
        print('Oh my lovely friend ' + vowelnames + '! ,I would like you to come on my graduation ceremony')
    else:
        for cons in friends[:8]:
            if cons in ('Bilal','Sarah','Zahid'):
                print( cons + " I would like you to come on my graduation ceremony")

1 个答案:

答案 0 :(得分:-1)

  

您必须使用“范围”

friends= ['Ali', 'Asma','Amna', 'Izma', 'Omer','Zahid','Bilal','Sarah']
for i in range(x): #Here instead of x you can give a number so that the loop will run 
                   #till that number
    for vowelnames in friends:
        if vowelnames in ('Ali','Asma','Izma','Omer'):
            print('Oh my lovely friend ' + vowelnames + '! ,I would like you to come 
                  on my graduation ceremony')
else:
    for cons in friends[:8]:
        if cons in ('Bilal','Sarah','Zahid'):
            print( cons + " I would like you to come on my graduation ceremony")