Alter888
Alter888

Reputation: 41

Make counter in Python

Is there a way to re-write my code using a counter? Something like: i=0, el=name[i+1]?? As code looks too long with lots of repeatings in it

 name = wait.until(EC.presence_of_all_elements_located((By.ID, 'com.eas.android:id/text_username')))
    try:
        if name:
            action.press(el=name[0]).wait(2000).perform()
            self.delUser()
            btnBack.click()
            time.sleep(2)
            action.press(el=name[1]).wait(2000).perform()
            self.delUser()
            btnBack.click()
            time.sleep(2)
            action.press(el=name[2]).wait(2000).perform()
            self.delUser()
            btnBack.click()
            time.sleep(2)
            action.press(el=name[3]).wait(2000).perform()
            self.delUser()
            btnBack.click()
            time.sleep(2)
            action.press(el=name[4]).wait(2000).perform()
            self.delUser()
            btnBack.click()
            time.sleep(2)
            action.press(el=name[5]).wait(2000).perform()
            self.delUser()
            btnBack.click()
            time.sleep(2)

Upvotes: 1

Views: 106

Answers (2)

LAS
LAS

Reputation: 819

try:
        if name:
           for i in range(6):
              action.press(el=name[i]).wait(2000).perform()
              self.delUser()
              btnBack.click()
              time.sleep(2)

  or

        if name:
           for i in range(len(name)):
              action.press(el=name[i]).wait(2000).perform()
              self.delUser()
              btnBack.click()
              time.sleep(2)

Upvotes: 1

Jack Wetherell
Jack Wetherell

Reputation: 585

The code could be simplified using a for loop:

    try:
        if name:
            for n in name:
                action.press(el=n).wait(2000).perform()
                self.delUser()
                btnBack.click()
                time.sleep(2)

Although, I would be careful as name seems to be a list, yet you are using it like a bool in the if-statement on line 2. (Correction: this is fine. See randomir's comment)

Upvotes: 4

Related Questions