Home > front end >  How do you close a function at the very end of a program?
How do you close a function at the very end of a program?

Time:12-06

I know this may be a stupid question but I am not sure how to use functions properly. For an assignment I had to come up with a program and it had to be written in the form of a function. Initially I started off doing it without the function format planning to add it at the very end but when I do so I get an error when I close the function at the very end. Could someone help me figure out what do I need to do please?


CodePudding user response:

It's not how you're "closing" (returning from) the function, but how you're calling it and how it's using the parameter.

Change:

def find_repeats(fname):
    file_name = "whatever.txt"

to:

def find_repeats(file_name):
    # don't set file_name to anything, it already has a value from the caller

so that the body of the function will use the file_name you pass in instead of a hardcoded one.

Now pass it in when you call the function by changing:

find_repeats(fname)  # this would error because what's fname?

to:

find_repeats("whatever.txt")

CodePudding user response:

I think this is what you are looking for

fname = "whatever.txt"

def find_repeats(fname):
    textfile = open(fname, "r")
    for line_number, line in enumerate(textfile):
        for x, y in zip(line.split(), line.split()[1:]):
            if(x==y):
                print(line_number,x,y,"Error")
    textfile.close() #function ends (close!) here


find_repeats(fname) #This is how you call above function
  • Related