Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing variables in Python

Tags:

python

I've been searching online for a while now and can't seem to find anything. I'm basically learning a few languages and I am just trying to recreate a program in different languages.

def read_one_file():
    f = open('C:\Python27\inventory.dat', 'r')
    invid = f.readline()
    stock = f.readline()
    published = f.readline()
    price = f.readline()
    invtype = f.readline()
    title = f.readline()
    author = f.readline()
    return invid, stock, published, price, invtype, title, author

read_one_file()

print "Update Number In Stock"
print "----------------------"
print "Item ID: ", invid

Basically I'm trying to read in a file, absorb the data into variables then pass those variables to the main(class?). When I return them they're still not able to be printed. When I initialize them outside of read_one_file they still don't return the right thing.

like image 406
Nogg Avatar asked Nov 23 '25 23:11

Nogg


1 Answers

You need to store the results of read_one_file() somewhere. What you're really doing with your return statement is creating a tuple of the results. You then have to unpack that tuple when you call read_one_file. Here is an example:

(invid, stock, published, price, invtype, title, author) = read_one_file()

print "Item ID:", invid

This syntax is performing something called "pattern matching" and what it does is break up the tuple that read_one_file returns and gives names to each of element in it. I added the parenthesis here to make it clearer that read_one_file is returning a tuple, but you could just as easily write it like this:

invid, stock, published, price, invtype, title, author = read_one_file()

That's all well and good, but really, this is sort of a bad way to return things from your function. If you have a lot of variables you want to return from a function like this, a dict is probably a better way to go. Also, you'll probably want to use a with statement to ensure your file is closed and cleaned up properly once you're done with it. Here is what your code would look like using that strategy:

def read_one_file():
    with open('C:\Python27\inventory.dat', 'r') as f:
        return dict(invid = f.readline().strip(),
                    stock = f.readline().strip(),
                    published = f.readline().strip(),
                    price = f.readline().strip(),
                    invtype = f.readline().strip(),
                    title = f.readline().strip(),
                    author = f.readline().strip())

results = read_one_file()

print "Update Number In Stock"
print "----------------------"
print "Item ID: ", results['invid']

Edit: I changed the code above to use .strip(), since (as @NiklasB. pointed out), newlines are still included with just readline.

like image 54
deontologician Avatar answered Nov 25 '25 11:11

deontologician