1

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)

2 Answers 2

4

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)

1
  • 1
    Try bool([]) and bool([1,2]). Non-empty lists in Python are truthy.
    – randomir
    Commented Aug 13, 2017 at 23:39
1
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)
2
  • 2
    range[0,5] is invalid syntax, I think you meant range(5), but to include the last value you should actually use range(6) Commented Aug 13, 2017 at 23:27
  • 2
    Or possibly, to keep it general range(len(name)). Commented Aug 13, 2017 at 23:35

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.