我試圖讓這個函式take_input在函式運行時添加到總數中。但是,當第二次添加費用時,我無法讓變數daily_expense累積。
def take_input():
daily_expense = 0
inp = int(input("How much did you spend?: "))
daily_expense = inp
print(f"Total expenses = {daily_expense}")
while True:
x = input("Add another expense? Y/N: ").lower()
if x == "y":
take_input()
elif x == "n":
break
else:
print("Please return a valid response")
def start_program():
start = input("Add expense? Y/N: ").lower()
if start == "y":
take_input()
start_program()
uj5u.com熱心網友回復:
這是作業代碼
def take_input(daily_expense:int):
inp = int(input("How much did you spend?: "))
daily_expense = inp
print(f"Total expenses = {daily_expense}")
while True:
x = input("Add another expense? Y/N: ").lower()
if x == "y":
take_input(daily_expense)
elif x == "n":
break
else:
print("Please return a valid response")
def start_program():
daily_expense = 0
start = input("Add expense? Y/N: ").lower()
if start == "y":
take_input(daily_expense)
start_program()
uj5u.com熱心網友回復:
您當前正在函式內部定義 daily_expense;這意味著每次呼叫 take_input() 時,您都將 daily_expense 重置為 0。
相反,您應該在函式之外定義 daily_expense,這樣它就不會每次都被重置;或者你應該在回圈中累積它,然后列印最終值,如下所示:
def take_input():
daily_expense = 0
more_expenses = input("Add expense? Y/N: ").lower()
while(more_expenses == "y"):
inp = int(input("How much did you spend?: "))
daily_expense = inp
more_expenses = input("Add expense? Y/N: ").lower()
if(more_expenses == "n"):
break
elif(more_expenses == "y"):
continue
else:
print("Please return a valid response")
more_expenses = input("Add expense? Y/N: ").lower()
print(f"Total expenses = {daily_expense}")
def start_program():
take_input()
start_program()
編輯:附加說明:
每次呼叫此函式時,該值都會再次重置并重新累積。
如果您想將此值存盤在資料庫中,那么我建議將其回傳,然后使用回傳的值更新資料庫條目,如下所示:
def take_input(): daily_expense = 0 more_expenses = input("Add expense? Y/N: ").lower() while(more_expenses == "y"): inp = int(input("How much did you spend?: ")) daily_expense = inp more_expenses = input("Add expense? Y/N: ").lower() if(more_expenses == "n"): break elif(more_expenses == "y"): continue else: print("Please return a valid response") more_expenses = input("Add expense? Y/N: ").lower() print(f"Total expenses = {daily_expense}") return daily_expense def start_program(): save_this_number_to_db = take_input() # store save this number into database start_program()
uj5u.com熱心網友回復:
使用while回圈而不是遞回來持續處理用戶輸入。
def start_program():
daily_expense = 0
extra = ""
while 1:
x = input(f"Add {extra}expense? Y/N: ").lower()
if x == "y":
inp = int(input("How much did you spend?: "))
daily_expense = inp
print(f"Total expenses = {daily_expense}")
extra = "another "
elif x == "n":
break
else:
print("Please return a valid response")
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/511290.html
標籤:Python功能变量
