2017-06-13 104 views
-5

下面是代碼:For循環蟒紋不同

start = 1 
end = 3 
a = "one" 
b = "two" 
for x in range(start, end + 1): 
    print a 
    print b 
    print b 
    print b 

輸出:

one 
two 
two 
two 
one 
two 
two 
two 
one 
two 
two 
two 

所需的輸出:

one 
two 
two 
two 
two 
one 
one 
one 
one 
two 
two 
two 

有人請幫助我獲得所需的輸出

第一時間打印一張,followe d三次b,第二次打印b,接着三次a,第三次打印a,接着三次b等等

回答

4

所以,基本上你希望a和b在後續迭代中切換位置。只是補充一點:

a, b = b, a 

在你的循環結束......

+0

正確的答案,另一個可能的建議是用循環改變重複的「打印b」。 –

0

基本上你正在做的是創造一個運行,它打印的代碼迴路,後隨b三次。然後這個代碼重複多次循環運行。你可以做的是使用一個布爾值,在每個循環之後在true和false之間變化。

start = 1 
end = 3 
a = "one" 
b = "two" 
Start_A = True 
for x in range(start, end + 1): 
if Start_A == True: 
    print a 
    print b 
    print b 
    print b 
    Start_A = False 
elif Start_A == False: 
    print b 
    print a 
    print a 
    print a 
    Start_A = True 

像這樣的東西會產生你想要的輸出。