Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python creating a list to find total revenue n times

Total revenue caluculated by increasing price by $5 n times and decreasing customers by 10 n times. here’s what I have so far

tr = []
startprice = 35
startpeople = 375
def r(num):
    for i in range(num):
        startprice = startprice + 5
        startpeople = startpeople - 10
        revenue = startprice * startpeople
        tr.append(revenue)
    return tr

It gives me the error "cannot access local variable ‘startprice’ where it is not #associated with a value"

Does anyone know how to fix it and make it work? -Thanks

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I’ve tried everything I know. ps. I’m a little new to python

>Solution :

You either need to pass global variables to your function via the function’s arguments or explicitly tell Python you’re using global variables.

tr = []
startprice = 35
startpeople = 375
def r(num):
    global startprice, startpeople, tr
    for i in range(num):
        startprice = startprice + 5
        startpeople = startpeople - 10
        revenue = startprice * startpeople
        tr.append(revenue)
    return tr

Keep in mind that doing this will modify the global variables, whereas if you pass them as arguments, they will be copied, and the global variables unchanged by a run of r.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading