我试图使用来自annual_salary函数的int输入来计算fed_tax函数的答案,但我一直得到一个错误,说从函数1保存的变量在函数2中未定义。
我知道工资是局部作用域,但我需要在下一个函数中与其他函数一起使用它。
def anual_salary():
salary = int(input("Enter your salary: "))
print(f"Gross income is ${salary}")
print(" ")
return salary
def fed_tax():
esbi = input("Are you an Employee, Self Employed, Business owner, or Investor? ")
if esbi == "Employee" or "employee":
fed_income_tax = .37 * salary
elif esbi == "Self Employed" or "self employed":
fed_income_tax = .35 * salary
elif esbi == "Business owner" or "business owner":
fed_income_tax = .20 * salary
elif esbi == "Investor" or "investor":
fed_income_tax = .15 * salary
else:
print("Incorrect answer!")
fed_income_tax = round(fed_income_tax, 2)
print(f"Your Federal Income Tax is ${fed_income_tax}")
print(" ")
return fed_income_tax
我做错了什么?
您需要调用函数并将值存储在fed_tax()的局部变量中。
def fed_tax():
salary = anual_salary()
esbi = input("Are you an Employee, Self Employed, Business owner, or Investor? ")
if esbi == "Employee" or "employee":
fed_income_tax = .37 * salary
elif esbi == "Self Employed" or "self employed":
fed_income_tax = .35 * salary
elif esbi == "Business owner" or "business owner":
fed_income_tax = .20 * salary
elif esbi == "Investor" or "investor":
fed_income_tax = .15 * salary
else:
print("Incorrect answer!")
fed_income_tax = round(fed_income_tax, 2)
print(f"Your Federal Income Tax is ${fed_income_tax}")
print(" ")
return fed_income_tax
你定义了一个函数,在这个函数中你请求一个工资,并且它被返回,所以,你要做的是在这个函数中,你发送调用请求它的类,按照下面的方式:
def fed_tax():
salary = anual_salary()
esbi = ....
if ....
fed_income_tax = .37 * salary
elif ...
fed_income_tax = .35 * salary
elif ....
fed_income_tax = .20 * salary
elif ....
fed_income_tax = .15 * salary
else:
print("Incorrect answer!")
fed_income_tax = round(fed_income_tax, 2)
print(f"Your Federal Income Tax is ${fed_income_tax}")
print(" ")
return fed_income_tax
您可以将该函数作为if/else的一部分调用,并避免将其作为单独的值存储
def fed_tax():
esbi = input("Are you an Employee, Self Employed, Business owner, or Investor? ")
if esbi == "Employee" or "employee":
fed_income_tax = 0.37* anual_salary()
elif esbi == "Self Employed" or "self employed":
fed_income_tax = .35 * anual_salary()
elif esbi == "Business owner" or "business owner":
fed_income_tax = .20 * anual_salary()
elif esbi == "Investor" or "investor":
fed_income_tax = .15 * anual_salary()
else:
print("Incorrect answer!")
fed_income_tax = round(fed_income_tax, 2)
print(f"Your Federal Income Tax is ${fed_income_tax}")
print(" ")
return fed_income_tax
<代码>代码>
如果您想在其他函数中使用annual_salary()
,您可以直接调用salary
。
PP_6如上所示,当您想将salary=annual_salary()
与其他函数一起使用时,只需添加CC_5即可调用它。