Jaf
Jaf

Reputation: 135

How do I send a variable back to the main program from a function?

I have a problem with my code

I want my code to return the name of a file created by a user command to my main program but I don't know how, I've tried return filename but that did not work, here is the code:

#File Creator 
def Create(filename):
    UserFile = open(str(filename), "wt")
    file = (str(filename))
    return file

#Main program
Create(input("filename: "))
print(file)

I'm using python 3.3, how do I set file as a variable that can be used from anywhere in the code?

I was thinking about adding file = Create(input("filename: ")) but I'm not sure if there is another way

Upvotes: 2

Views: 274

Answers (2)

user2555451
user2555451

Reputation:

You can use global:

def Create(filename):
    global file
    UserFile = open(str(filename), "wt")
    file = (str(filename))
    #return file  -- I commented this since there is no real reason to return now with a global

file will now be in the global scope.

Personally though I think your method of file = Create(input("filename: ")) is the best. Using globals like that is frowned upon by many and can quite often be avoided.

Upvotes: 0

Óscar López
Óscar López

Reputation: 236004

How come returning the file didn't work? although you have several mistakes in the code. Try this, it should do the trick:

# File Creator 
def create(filename):
    userFile = open(filename, "rw")
    return userFile # this is a file object

# Main program
theFile = create(input("filename: "))
print(str(theFile)) # string representation of the file object

By all means, avoid using global variables if there's no real need for them - global variables are a very bad programming practice. In this simple case it suffices to pass values as parameters and/or return values, in a well-structured program that should be enough for your needs.

Upvotes: 3

Related Questions