dpx dpx - 6 months ago 11
Python Question

Returning multiple values from function in python 3.5

I'm trying to get some help in returning values from "year_calc" function below (Python 3.5). In essence, the code works for returning "b" as I need a new starting value for "b" to be passed to "year_calc" for each iteration - I can get that to work just fine. However, I want the "total_cost" value from each year_calc iteration to be returned and added up until finished. Note the "grand_total" under the while loop. I realize this doesn't work as stated - just adding it so it may add clarity to what I'm attempting to accomplish. I am just not sure how to pull a specific value which is being returned. Any insight?

def main():
archive_total = float(input('Enter archive total (GB): '))
transfer_rate = float(input('Enter transfer rate (Gbps): '))
days_to_transfer = ((((archive_total*8/transfer_rate)/60)/60)/24)
xfer_per_day = archive_total/days_to_transfer
day_cost = xfer_per_day * 0.007 / 30
days = 365
total_days = 0
sum = 0
b = xfer_per_day * 0.007 / 30
total_years = 1
grand_total = 0.0
total_cost = 0.0
while total_years < years_to_transfer + 1:
b = year_calc(day_cost, days, total_days, sum,b,total_years,total_cost)
total_years += 1
grand_total += total_cost

def year_calc(day_cost,days,total_days,sum,b,total_years,total_cost):
while total_days < days -1:
b += day_cost
sum += b
total_days += 1
total_cost = sum + day_cost
print('Year',total_years,'cost: $', format(sum + day_cost, ',.2f'))
return (b, total_cost)

main()

Answer

year_calc, as with any function that returns multiple items, will return its values in a tuple. Therefore, you can just change this line:

b = year_calc(day_cost, days, total_days, sum,b,total_years,total_cost)

to this one:

b, total_cost = year_calc(day_cost, days, total_days, sum,b,total_years)

This works because of how Python handles multiple assignment:

>> a, b = 1,2
>> print a
1
>> print b
2

As an aside, you should try to avoid using builtin names like sum for your variables. And I'm not sure what years_to_transfer is - do you define that elsewhere in your code?

Comments