我试图从" year_calc"中返回值来获得一些帮助。下面的函数(Python 3.5)。本质上,代码适用于返回" b"因为我需要一个新的起始值" b"被传递给" year_calc"对于每次迭代 - 我可以让它工作得很好。但是,我想要" total_cost"每年year_calc迭代的值将被返回并累加直到完成。注意" grand_total"在while循环下。我意识到这并没有按照规定工作 - 只需添加它就可以增加我试图完成的内容的清晰度。我只是不确定如何提取正在返回的特定值。任何见解?
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()
答案 0 :(得分:1)
如果我正确理解了你的描述,这可以实现你想要的:
def main():
# ...
total_cost = 0.0
while total_years < years_to_transfer + 1:
b, total_cost = year_calc(day_cost, days, total_days, sum,b,total_years,total_cost)
# ...
def year_calc(day_cost,days,total_days,sum,b,total_years,total_cost):
# ...
return (b, total_cost)
main()
答案 1 :(得分:1)
year_calc
将在元组中返回其值。因此,您只需更改此行:
b = year_calc(day_cost, days, total_days, sum,b,total_years,total_cost)
到这一个:
b, total_cost = year_calc(day_cost, days, total_days, sum,b,total_years)
这是有效的,因为Python处理多个赋值:
>> a, b = 1,2
>> print a
1
>> print b
2
另外,您应该尽量避免为变量使用内置名称sum
。而且我不确定years_to_transfer
是什么 - 你在代码的其他地方定义了吗?
答案 2 :(得分:1)
嗯,好像有点像在Python中编写VBA代码......: - )
好的,首先:我认为您不想将total_cost传递给函数year_calc,因为您不依赖于您获得的任何值。所以从定义行中删除它:
def year_calc(day_cost,days,total_days,sum,b,total_years):
...
下一步:你为total_cost计算一个新值并从函数中返回一个tupple。这是非常正确的。
现在,当callin year_calc你应该从调用函数中删除total_cost变量。但你应该记住你返回一个tupple,所以将值赋给tupple:
(b, total_cost) = year_calc(day_cost, days, total_days, sum,b,total_years)
底线:没有在python中的函数中发送的ref变量(或输出变量,...)。放入参数,仅此而已。如果要返回2个不同的计算,请返回一个tupple,但也将该值赋给tupple。更干净。