2017-02-16 131 views
-3

我想用這些代碼做一個循環。有X個行數。如何在Python中循環if語句?

if line[3]>=15: 
    line[3]=0 
    print("line 3 is >= 15") 
    if line[2]>=15: 
     line[2]=0 
     print("line 2 is >= 15") 
     if line[1]>=15: 
      line[1]=0 
      print("line 1 is >= 15") 
      if line[0]>=15: 
       print("FFFFF") 
      else: 
       line[0]+=1 
     else: 
      line[1]+=1 
    else: 
     line[2]+=1 
else: 
    line[3]+=1 

我想要一個循環,使該代碼適用於X數量的代碼。

我想要完成的就像line [4]> = 15那麼line [4]將是0,然後將1加到line [3]。

但我想要一個循環..如果我想有超過4行,那麼我將只編輯我想要的行數,而不是再添加額外的if語句。

+0

我認爲你得到低價的原因是你沒有在你的描述中提供足夠的細節!如果你可以添加更多的細節和解釋你正在尋找什麼,這將大大緩解溝通。 – Marviel

+1

你需要充分解釋你想要做什麼。這非常含糊。 – Carcigenicate

+0

嗨,大家好,感謝您的評論,我已經編輯過它,希望它不再模糊。 –

回答

0

我不得不承認,我不確定這是你想做什麼,但這是我根據你的代碼/評論理解的。

for i in range(len(line)-1, -1, -1): 
    if line[i] >= 15: 
     line[i] = 0 
     if i != 0: 
      print("line {} is >=15".format(i)) 
     else: 
      print("FFFFF") 
    else: 
     line[i-1] +=1 
+0

這是最接近我需要的。我已經找到了我需要的代碼。非常感謝你! –

0

我可能是錯的,但你的代碼讓我想到遞歸序列。如果它是遞歸序列,則應該查看python中的遞歸函數:http://www.python-course.eu/recursive_functions.php

從我的理解如果line=[1,36,13,17]那麼我們應該得到line=[2, 0, 14, 0]

這裏是遞歸函數我做:

def test(line,n): 
    if n==0: # 2) and for the last it will run here 
     if line[0]>=15: 
      print("FFFFF") 
     else: 
      line[0]+=1 
     print line 
     return "the end" 
    else: # 1) for all calculations the program will run here 
     if line[n]>=15: 
      line[n]=0 
      print("line " + str(n) + " is >= 15") 
      return test(line,n-1) 
     else: 
      line[n]+=1 
      return test(line,n-1) 

line=[1,36,13,17] 

print test(line,3) 

下面是結果:

line 3 is >= 15 
line 1 is >= 15 
[2, 0, 14, 0] 
the end 

不過我覺得你不需要做任何遞歸序列做這樣的事情。你應該遵循bouletta做的事情。

+0

感謝您的支持!雖然這不是我想要的那是因爲我的問題並不清楚。但我從中學到了一些東西。謝謝! –