python - Creating a Function to sum the results of an equation. Please look, Not so simple? -
i'm new programming , started using website. can't find similar simple problem. i'm using phyton 3.3. i'm creating code measures solar intensity on solar panels. did initially, decided make equations more complex better reflect real world situations.
i'm putting simplified equation similar problem encountered:
total=0 def equation(): x=2+i total+=x print (total) in range(1,32): #represents no of days in january (31 days) equation() in range (32,61): #represents no.of days in february (28days) equation() etc....for months
this problem("total+=x). cannot add results x. error says "total" referenced before assignment. reference within function give me results (x) each iteration, not sum of iterations.
the real equation contains more 15 lines of formulas. want insert equation onto different ranges (all 12 months of year). don't want copy , paste huge formula under each range. messy. prefer more efficient solution , reuse code. far i'm scratching head.
i've considered using built-in sum function instead of "total+" , finding various ways using 'while' loop circumvent problem. no luck
i'm learning classes , using oop in python. still trying understand concepts. believe basics should cover problem. don't know how. i've been struggling @ days trying work around problem.your appreciated.
if not being clear, please forgive me. try clarify questions have.
thanks
zac
you should change function take i
input. , move summation out of function.
total=0 def equation(i): x=2+i return x in range(1,32): #represents no of days in january (31 days) total += equation(i) print total
or way list comprehensions.
#or total += sum(equation(i) in range(1,32)) print total
Comments
Post a Comment