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

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.

Leave a Reply