我需要帮助使此循环正常工作吗?

时间:2019-05-09 08:25:22

标签: python

我需要帮助使函数推论中的循环起作用。

我尝试着研究类似的关于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”。然后继续要求扣除。

1 个答案:

答案 0 :(得分:0)

我认为您的代码中有几个错误:

正如评论中指出的那样,据我了解您正在尝试执行的操作,应使用while not (choice == "Y" or choice == "N")

您似乎忘记了TotalTax = Tax + TotalInsurance

try/except不会从输入中抛出ValueError,因此您要查找的可能是elseif之后的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,因为您已经将它退回了,但是也许您有充分的理由。