How to reset counter in Python

Hi I’m new to programming, i have a program that will count name start from 1 to the range of a data. My problem is the counter will continue to add the previous name. For example, when i run file 1 , it will show a,b,c , but when i run the second file the name will start from d,e,f. What i want is to reset the counter value to A whenever i choose a new file.

My code

num = 0
def countname():
    global num
    num += 1
    return str(num)

def change():
  for content in data2:
     filename = "" + "Name" + " " + countname()
     print(filename)

Answer

Your problem is somewhere else in your code – not in the shown parts – they work:

num = 0
def countname():
    global num
    num += 1
    return str(num)

def change(data2):
    for content in data2:  
        filename = "" + "Name" + " " + countname()
        print(filename)

# the content (a,b, etc. is currently ignored)
change ("a b c d e f".split())

Output:

Name 1  
Name 2
Name 3
Name 4
Name 5
Name 6

A better version without global would be:

def change_better(data2):
    # start indexing at 1 and loop over index,datapoints
    for index, content in enumerate(data2, 1):
        filename = f"Name {index}"
        print(filename)

change_better ("a b c d e f".split())

wich genenerates the same output as above.

change ("a b c d e f".split())

Your real issue is not shown, code as this is not a minimal reproduceable example that replicates your problem.

My hunch would be that you somewhere add this created filename to some other thing (f.e. a path) and you use that to create the file. And there is the problem with repeating names.

See String formatting: % vs. .format vs. string literal for f-style string literal formatting

Leave a Reply

Your email address will not be published. Required fields are marked *