我需要帮助让这个循环正常工作?

2024-09-30 01:19:17 发布

您现在位置: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”。然后继续要求扣除。你知道吗


Tags: ortoloopyouinputtaxprintchoice
1条回答
网友
1楼 · 发布于 2024-09-30 01:19:17

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

正如在评论中指出的那样,根据我的理解,您应该使用while not (choice == "Y" or choice == "N")。你知道吗

你好像忘了TotalTax = Tax + TotalInsurance。你知道吗

try/except不会从输入中抛出ValueError,因此您要查找的可能是ifelif之后的else子句。你知道吗

choice == "Y"是布尔值,它不设置值。你在找choice = "Y"。你知道吗

我认为当您在第二个while循环中使用choice变量,然后使用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。你知道吗

另外,在input前面不需要str,因为input已经在python3中返回了一个str对象。你知道吗

我也不知道你为什么需要global TotalDed,因为你已经退了,但也许你有一个很好的理由。你知道吗

相关问题 更多 >

    热门问题