我是 Python 的初學者,并且正在為我正在從事的專案而苦苦掙扎。該程式獲取月收入、每月固定費用、要求任何額外費用,然后輸出 if else 陳述句。我的問題在于這個功能:
def spending(income, totals):
finalTotal = income - totals
if income > finalTotal:
print("You saved $", "%.2f"%finalTotal, "this month!")
elif finalTotal > income:
print("You overspent by $", "%.2f"%finalTotal, "this month!")
else:
print("You broke even this month!")
它正在列印:
You saved $ -805.00 this month!
當我想列印時:
You overspent by $ 805.00 this month!
任何反饋將不勝感激!!
這是我的代碼: https ://replit.com/@ashleyshubin/BudgetProgram#main.py
uj5u.com熱心網友回復:
如果總計是您的每月支出,那么從收入中減去總計可以得出您本月賺了多少錢。第一個 if 陳述句應該是
if finalTotal > 0:
第二個 if 陳述句是
if finalTotal < 0:
你會想在列印 finalTotal 時使用 abs(finalTotal) ,這樣它就不會顯示負數
uj5u.com熱心網友回復:
你的支票是錯的。您可以執行以下操作:
def spending(income, totals):
finalTotal = income - totals
if income > totals:
print("You saved $", "%.2f"%finalTotal, "this month!")
elif totals > income:
print("You overspent by $", "%.2f"%-finalTotal, "this month!")
else:
print("You broke even this month!")
uj5u.com熱心網友回復:
這部分是出錯的地方:
finalTotal = income - totals
if income > finalTotal:
print("You saved $", "%.2f"%finalTotal, "this month!")
看起來您在“if”陳述句中比較了錯誤的變數。你的“finalTotal”變數已經包含了你的收入。把它想象成 alegbra,用“income - totals”替換“finalTotal”,你的 if 陳述句現在看起來像:
if income > (income - totals):
無論您使用什么值,此陳述句將始終評估為 true。您可能想要重寫您的 if 陳述句來比較“收入 > 總計”,而不是 finalTotal。
uj5u.com熱心網友回復:
您的比較應該基于 finaltotal ,因為 fialtotal 是finalTotal = income - totals,也else 永遠不會根據代碼中的其他條件運行:
def spending(income, totals):
finalTotal = income - totals
if finalTotal > 0:
print("You saved $", "%.2f" % finalTotal, "this month!")
else:
print("You overspent by $", "%.2f" % abs(finalTotal), "this month!")
uj5u.com熱心網友回復:
您應該將收入與總支出進行比較。
def spending(income, totals):
finalTotal = abs(income - totals)
if totals < income:
print("You saved $", "%.2f"%finalTotal, "this month!")
elif totals > income:
print("You overspent by $", "%.2f"%finalTotal, "this month!")
else:
print("You broke even this month!")
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/427567.html
上一篇:重復ifelse塊
