1

The below code block returns the data I want, however I have called 'read_from_file(filename) from outside the if statement, where filename doesn't exist.

I know I have two options to improve this:

  1. call read_from_file(filename) from inside my if statement, or
  2. make filename a global variable.

However when I attempt both I run into other issues such as the text from the file not returning. Would someone be able to show the correct way to do one of the above options?

filename = input('input the filename: ')
#read the file
def read_from_file(filename):
    content = []
    with open(filename, "r") as file:
        for line in file:
            line = line.strip()
            if "-" not in line:
                content.append(float(line))
    return content

print(read_from_file(filename))

1 Answer 1

2

You can remove the file_name parameter from read_from_file and get the file name from inside the function

def read_from_file():
    filename = input('input the filename: ')

print(read_from_file())
Sign up to request clarification or add additional context in comments.

4 Comments

just curious, what does signature mean in this context? Is it dfferent than a function's defnition?
Hi Guy, I understand I can move filename = input('input the filename: ') to inside the function but if I do that I am then having trouble on how I print/return the results inside the function. As if I move the input inside the function I can no longer have the print function globally
@TC1111 why not? the function returns the content and you print the returned value. Notice I removed filename from both the function parameters and the function call.
Thanks Guy! the removing the filename from the first line in the function is what i missed

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.