2015-12-29 33 views
-6

我想用某種循環縮短這段代碼:for,if(inside if),while,foreach,or other one。我該如何縮短這個python代碼

def FindChannel(): 
    rc_program_up = "Ch+" 
    rc_ok = "ok" 
    rc_exit = "exit" 
    value0 = checkPicture(15) 

    if (value0 == 100): 
     send_rckey(rc_exit) 
    else: 
     send_rckey(rc_program_up) 
     value0 = checkPicture(15) 

    if (value0 == 100): 
     send_rckey(rc_exit) 
    else: 
     send_rckey(rc_program_up) 
     value0 = checkPicture(15) 

    if (value0 == 100): 
     send_rckey(rc_exit) 
    else: 
     send_rckey(rc_program_up) 
     value0 = checkPicture(15) 

    if (value0 == 100): 
     send_rckey(rc_exit) 
    else: 
     send_rckey(rc_program_up) 
     value0 = checkPicture(15) 

    if (value0 == 100): 
     send_rckey(rc_exit) 
    else: 
     send_rckey(rc_program_up) 
     value0 = checkPicture(15) 

我不能這樣做,請幫助我。

+1

修復縮進,請 – n4nn31355

+3

你只是重複相同的5行代碼5次? – khelwood

+0

你可以嘗試使用'elif'。 https://docs.python.org/2/tutorial/controlflow.html#if-statements –

回答

3

您可以使用for循環。 range(5)循環5次,無論它在裏面。該_是表示你不想使用由迭代器返回的值(在這種情況下range(5)

for _ in range(5): 
    if (value0 == 100): 
     send_rckey(rc_exit) 
    else: 
     send_rckey(rc_program_up) 
     value0 = checkPicture(15) 

爲了更好地理解有關for環看documentation(注:xrange只是個面向Python 2,在Python 3 range相當於xrange

0

我喜歡保持特定使用常數的一類,像

class Remote: 
    GET_CHANNEL = 15 
    CHANNEL_UP = "Ch+" 
    OK = "ok" 
    EXIT = "exit" 

    def up_to_channel(self, wanted_channel, max_ups=5): 
     for _ in range(max_ups): 
      this_channel = checkPicture(Remote.GET_CHANNEL) 
      if this_channel == wanted_channel: 
       send_rckey(Remote.EXIT) 
       return True # Success 
      else: 
       send_rckey(Remote.CHANNEL_UP) 
     # didn't find it 
     return False # Failure