[英]Python: How to increase count for a code every time a function is run
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.我正在尝试将 function 添加到我的项目中,其中初始值从零开始,每次运行此 function 时它都会递增 1。这里的问题是我不希望它重置为零,除非项目的数据库被重置。
def serial_code():
count = 0
count += 1
return count
print(serial_code())
You have 1 option and that option is to use file.您有 1 个选项,该选项是使用文件。
Create a new .txt
file in your directory, let's call it count.txt
and then put 0
into that file.在您的目录中创建一个新的
.txt
文件,我们将其命名为count.txt
,然后将0
放入该文件中。
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.首先我们以读取模式打开文件以从文件中读取数据,该文件为
0
,然后将 0 赋值给count
变量并关闭文件。
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.其次,再次打开文件,但这次是写模式(我们这样做是因为写模式将重写整个内容),然后增加 1,写入文件,然后关闭文件。
Now whenever you call the function the value inside file will increase by 1. 0 -> 1 -> 2 -> 3.....现在,无论何时调用 function,文件中的值都会增加 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
:您可以使用
global
-关键字为应该在 function 的 scope 之后持续存在的变量执行此操作。初始化一次后,每次调用f
时,以下代码中的变量i
都会增加:
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.查看您在 function 本身中声明变量的代码,这就是为什么它总是在外部重置声明的原因。 And make the variable global
并使变量全局
count = 0
def serial_code():
global count
count += 1
return count
print(serial_code())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.