-6

I want to shorten this code using some kind of loop: for, if(inside if), while, foreach, or another one.

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)

I can not do it, please help me.

200_success
  • 7,286
  • 1
  • 43
  • 74

2 Answers2

3

You can use a for loop. range(5) loops 5 times whatever is inside it. The _ is to indicate that you don't want to use the value returned by the iterator (In this case range(5))

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

For better understanding about for loop look at the documentation (Note: xrange is only for Python 2, in Python 3 range is equivalent to xrange)

Mr. E
  • 2,070
  • 11
  • 23
0

I like to keep use-specific constants in a class, like

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
Hugh Bothwell
  • 55,315
  • 8
  • 84
  • 99