I am trying to add a function to my project where initial it starts with zero and every time this function is run it increments by 1. The issue here is that I don't want it to reset to zero except if the database of the project is reset.
def serial_code():
count = 0
count += 1
return count
print(serial_code())
You have 1 option and that option is to use file.
Create a new .txt
file in your directory, let's call it count.txt
and then put 0
into that file.
def serial_code():
called = True
if called:
count_file = open("count.txt", "r") # open file in read mode
count = count_file.read() # read data
count_file.close() # close file
count_file = open("count.txt", "w") # open file again but in write mode
count = int(count) + 1 # increase the count value by add 1
count_file.write(str(count)) # write count to file
count_file.close() # close file
return count
First we open file in read mode to read data from the file which is 0
then assign 0 into count
variable and close the file.
Second, open file back again but in write mode this time (we do this because write mode will rewrite the whole content), then increase 1, write to file, and close file.
Now whenever you call the function the value inside file will increase by 1. 0 -> 1 -> 2 -> 3.....
You can do this using the global
-keyword for the variable that should persist beyond the scope of the function. After being initialised once, the variable i
in the following code is increased with every call to f
:
i = 0
def f():
global i
i += 1
for _ in range(100):
f()
print(i)
See your code that u declare the variable in the function itself that's why it always reset declare it outside. And make the variable global
count = 0
def serial_code():
global count
count += 1
return count
print(serial_code())
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.