我對我的代碼感到困惑,我認為我做的一切都是正確的,但我不確定如何讓我的代碼的第二部分作業,即“total_costs”函式。我現在已經觀看了很多視頻,但似乎找不到一個關于此的視頻,有人可以向我解釋為什么我的代碼的第二部分無法作業嗎?
def get_input():
e1 = float(input("What is the monthly expense for House Payment. "))
e2 = float(input("What is the monthly expense for Homeowners Insurance. "))
e3 = float(input("What is the monthly expense for Car Payments. "))
e4 = float(input("What is the monthly expense for Car Insurance. "))
e5 = float(input("What is the monthly expense for Utilities. "))
print("The monthly expenses total to",format(monthly, ',.2f'))
print("The yearly expenses total to",format(yearly, ',.2f'))
def total_costs():
monthly = e1 e2 e3 e4 e5
yearly = monthly * 12
return monthly, yearly
get_input()
uj5u.com熱心網友回復:
您使用 e1,e2,e3,e4,e5 作為函式變數,因此作用域僅限于get_input函式,您不能在get_input函式之外使用這些變數,除非您全域指定它們。
此外,您不是在呼叫total_cost函式。
問題是您在區域范圍內使用變數而不是呼叫函式。
uj5u.com熱心網友回復:
您的代碼存在一些問題。首先,您沒有呼叫total_costs(),因此它永遠不會被執行。您也沒有捕獲結果。
讓我們重新安排一下:
def get_input():
e1 = float(input("What is the monthly expense for House Payment. "))
e2 = float(input("What is the monthly expense for Homeowners Insurance. "))
e3 = float(input("What is the monthly expense for Car Payments. "))
e4 = float(input("What is the monthly expense for Car Insurance. "))
e5 = float(input("What is the monthly expense for Utilities. "))
monthly, yearly = total_costs()
print("The monthly expenses total to",format(monthly, ',.2f'))
print("The yearly expenses total to",format(yearly, ',.2f'))
def total_costs():
monthly = e1 e2 e3 e4 e5
yearly = monthly * 12
return monthly, yearly
get_input()
更好,但是當您嘗試時,它會抱怨不知道 e1。那是因為盡管看起來是這樣,但 total_costs 不知道e1和 其他變數。您需要明確地傳遞它。
#!/usr/bin/env python3
def get_input():
e1 = float(input("What is the monthly expense for House Payment. "))
e2 = float(input("What is the monthly expense for Homeowners Insurance. "))
e3 = float(input("What is the monthly expense for Car Payments. "))
e4 = float(input("What is the monthly expense for Car Insurance. "))
e5 = float(input("What is the monthly expense for Utilities. "))
monthly, yearly = total_costs(e1, e2, e3, e4, e5)
print("The monthly expenses total to",format(monthly, ',.2f'))
print("The yearly expenses total to",format(yearly, ',.2f'))
def total_costs(e1, e2, e3, e4, e5):
monthly = e1 e2 e3 e4 e5
yearly = monthly * 12
return monthly, yearly
get_input()
現在一切都像您期望的那樣作業。現在您不必像這樣構建代碼。例如,感覺您所做的get_input事情不需要它自己的函式,也許相反,擁有所有這些單個變數,例如e1,您可以擁有一個像串列或字典這樣的結構,您可以將其傳遞給total_costs,但您會學到那很快。
uj5u.com熱心網友回復:
沒有地方total_costs叫它。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/367026.html
