我需要帮助使函数推论中的循环起作用。
我尝试着研究类似的关于stackoverflow的问题,但是我一直努力解决这些问题。
def Deductions(money, Tax, TotalInsurance):
deductions = 0
global TotalDed
TotalDed = 0
choice = ""
while not choice == "Y" or choice == "N":
try:
choice = str(input("Do you want to add any more deductions to your income, e.g car, rent or mortgage? Y/N : "))
except ValueError:
print("Must enter Y or N")
if choice == "Y":
while choice == "Y":
AddDed = int(input("How much would you like to deduct: "))
deductions = AddDed + deductions
loop = str(input("Would you like to add more deductions? Y/N: "))
if loop == "Y":
choice == "Y"
elif loop == "N":
choice =="N"
elif choice == "N":
TotalDed = TotalTax + deductions
print("Income: £", money)
print("Taxed: £", Tax)
print("National Insurance: £", TotalInsurance)
print("Other Deductions: £", deductions)
print("Total Deductions: £", TotalDed)
return TotalDed
我要确保我的循环仅接受“ Y”和“ N”。然后继续要求扣除。
答案 0 :(得分:0)
正如评论中指出的那样,据我了解您正在尝试执行的操作,应使用while not (choice == "Y" or choice == "N")
。
您似乎忘记了TotalTax = Tax + TotalInsurance
。
try/except
不会从输入中抛出ValueError
,因此您要查找的可能是else
和if
之后的elif
子句。
choice == "Y"
是布尔值,它没有设置值。您正在寻找choice = "Y"
。
我认为在第二个choice
循环中使用while
变量,然后使用loop
将值设置为choice
时感到困惑。下面是我要选择要执行的操作的另一种结构。
您还可以针对input
语句中可能出现的错误值添加更多保护。
总结起来,这是我认为你应该写的:
def Deductions(money, Tax, TotalInsurance):
deductions = 0
global TotalDed
TotalDed = 0
TotalTax = Tax + TotalInsurance
choice = ""
while choice != "N":
choice = input("Do you want to add any more deductions to your income, e.g car, rent or mortgage? Y/N : ")
if choice == "Y":
AddDed = float(input("How much would you like to deduct: "))
deductions = AddDed + deductions
elif choice != "N":
print("Must enter Y or N")
TotalDed = TotalTax + deductions
print("Income: £", money)
print("Taxed: £", Tax)
print("National Insurance: £", TotalInsurance)
print("Other Deductions: £", deductions)
print("Total Deductions: £", TotalDed)
return TotalDed
也
AddDed = float(input("How much would you like to deduct: "))
deductions = AddDed + deductions
可以替换为
valid_added_value = False
while not valid_added_value:
try:
AddDed = float(input("How much would you like to deduct: "))
valid_added_value = True
except ValueError:
print('Must be a numerical value')
deductions = AddDed + deductions
提供额外的保护,因为它可能会抛出ValueError
。
此外,您不需要str
前面的input
,因为input
已经在python3中返回了str
对象。
我不确定您为什么需要global TotalDed
,因为您已经将它退回了,但是也许您有充分的理由。