简体   繁体   中英

How do i increase the value of an variable in a command line?

a = 1
for i in range(5):
    browser.find_element_by_xpath("/html/body/div[6]/div/div/div[2]/div/div/div[1]/div[3]/button").click()
    sleep(1)

I want to increase the 1 in div[1] by 1+ every loop, but how can i do that?

i thought i need to add a value, do "+a+" and last of all a "a = a + 1" to increase the value every time, but it didnt worked.

a = 1
for i in range(5):
    browser.find_element_by_xpath("/html/body/div[6]/div/div/div[2]/div/div/div["+a+"]/div[3]/button").click()
    a = a + 1
    sleep(1)
for i in range(1,6):
    browser.find_element_by_xpath("/html/body/div[6]/div/div/div[2]/div/div/div["+str(i)+"]/div[3]/button").click()
    sleep(1)

you don't need 2 variables, just one variable i in the loop, convert it to string with str() and add it to where you need it, pretty simple. the value of i increases for every iteration of the loop going from 1 to 5 doing exactly what you need.

alternatively to Elyes' answer, you can use the 'global' keyword at the top of your function then a should increment 'correctly'.

You don't really need two variables for this unless you are going to use the second variable for something. However, look at the following code and it will show you that both i and a will give you the same result:

from time import sleep

a = 1
for i in range(1, 6):
    path = "/html/body/div[6]/div/div/div[2]/div/div/div[{idx}]/div[3]/button".format(idx=i)
    print(path, 'using i')
    path = "/html/body/div[6]/div/div/div[2]/div/div/div[{idx}]/div[3]/button".format(idx=a)
    a += 1
    print(path, 'using a')
    sleep(1)

Result:

/html/body/div[6]/div/div/div[2]/div/div/div[1]/div[3]/button using i
/html/body/div[6]/div/div/div[2]/div/div/div[1]/div[3]/button using a
/html/body/div[6]/div/div/div[2]/div/div/div[2]/div[3]/button using i
/html/body/div[6]/div/div/div[2]/div/div/div[2]/div[3]/button using a
/html/body/div[6]/div/div/div[2]/div/div/div[3]/div[3]/button using i
/html/body/div[6]/div/div/div[2]/div/div/div[3]/div[3]/button using a
/html/body/div[6]/div/div/div[2]/div/div/div[4]/div[3]/button using i
/html/body/div[6]/div/div/div[2]/div/div/div[4]/div[3]/button using a
/html/body/div[6]/div/div/div[2]/div/div/div[5]/div[3]/button using i
/html/body/div[6]/div/div/div[2]/div/div/div[5]/div[3]/button using a

You can read up on range here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM