[英]incrementing inside a function python
我正在做一個初學者 python 課程並創建了一個非常簡單的 function ,它告訴您考慮到回程航班費用、酒店費用(每天)和汽車租賃費用(每周),您的假期費用是多少。
這很好,但是下一步是找出在預算為 1000 的情況下您可以在一個國家停留多長時間。
我的邏輯是從 1 開始持續時間並嘗試讓 function 運行並檢查cost_of_trip
是否小於 1000。如果是,它將增加持續時間並再次運行。 一旦cost_of_trip
超過 1000,它將停止並返回之前的持續時間值。 嘗試了幾個while循環,但不能讓它增加一次以上。
這是基本的 function
import math
def duration_function (return_flight,hotel_cost,car_rental,):
duration = 1
car_rental = math.ceil((duration/7)) * car_rental
cost_of_trip = return_flight + (hotel_cost * duration) + car_rental
while cost_of_trip <=1000:
duration += 1
return duration
嘗試了這個while循環的幾個版本
一個示例輸入是
london_duration = duration_function(
hotel_cost = 30,
car_rental = 120,
return_flight = 250,
)
print ("London: " + str(london_duration))
對於上面列出的 function,這只是作為無限循環運行。
這將起作用
def duration_function (return_flight,hotel_cost,car_rental):
duration = 1
cost_of_trip= 0
while(cost_of_trip < 1000 ):
car_rental = math.ceil((duration/7)) * car_rental
cost_of_trip = return_flight + (hotel_cost * duration) + car_rental
duration+=1
return duration
這個怎么樣? 我不確定,如果它是你想要的,我在這個可怕的控制台中做到了,但試試吧。 (第一次調用此方法時,將“cost_of_trip”設置為 0)
import math
def duration_function (return_flight,hotel_cost,car_rental,duration, cost_of_trip):
previous = cost_of_trip
car_rental = math.ceil((duration/7)) * car_rental
cost_of_trip = return_flight + (hotel_cost * duration) + car_rental
if cost_of_trip < 1000:
duration++
duration_function(return_flight,hotel_cost,car_rental,duration, cost_of_trip)
else:
if (revious == 0):
print("you have not enought money for this trip")
else:
return previous
您的duration_function
沒有return
語句,因此它永遠不會起作用。 我建議如下:
def duration_function(budget, return_flight, hotel_cost, car_rental): # also pass the available budget
budget = budget - return_flight
days = 0
while budget > 0:
if days % 7 == 0: # add weekly car rental
budget -= car_rental
budget -= hotel_cost # add daily hotel fee
if budget > 0:
# only add the day count if any money left
days += 1
return days
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.