简体   繁体   中英

i am trying to increase my number by 1 every time my code runs

the problem i'm having is that every time i go to a new function and then go back to the first one, the count starts over. yo(driver) random(driver) yo(driver) . the second time i do yo(driver) the count starts over and if i place count = 0 outside of the function then it comes up as an unresolved reference inside of the function. is there any simple way i can get it keep counting and not start over?

timeout = time.time()+2

def yo(driver):
count = 0
while True:
    try:
        print("try 1")
        count += 1
    except:
        print("except 1")
    else:
        print("else 1")
    finally:
        print("finally 1")
        if time.time() > timeout:
            print("timeout")
            print("count", count)
            break

def random(driver):
    print("yoyo")

yo(driver)
random(driver)
yo(driver)

'''

Try this, you can declare a method specific variable and have its state be updated each time you change it during method invocation.

def yo():
    yo.count += 1
    print(yo.count)

yo.count = 0

yo()
yo()

Output:

1
2
import time

timeout = time.time()+2

def yo():
    while True:
        try:
            print("try 1")
            yo.count += 1
        except:
            print("except 1")
        else:
            print("else 1")
        finally:
            print("finally 1")
            if time.time() > timeout:
                print("timeout")
                print("count", yo.count)
                break
yo.count = 0
yo()

You can define count as a global variable, and define it a global inside your function:

count = 0

def yo(driver):
     global count
     while True:
          try:
               print("try 1")
               count += 1
          except:
               print("except 1")
          else:
               print("else 1")
          finally:
               print("finally 1")
               if time.time() > timeout:
                    print("timeout")
                    print("count", count)
                    break

Or you can pass it as a function argument:

def yo(driver, count):
     while True:
          try:
               print("try 1")
               count += 1
          except:
               print("except 1")
          else:
               print("else 1")
          finally:
               print("finally 1")
               if time.time() > timeout:
                    print("timeout")
                    print("count", count)
                    break
    return count
count = 0
count = yo(driver, count)
random(driver)
count = yo(driver, count)

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