Python 3+:即使用户输入按钮停止循环,循环仍继续要求用户输入费用。

时间:2017-03-12 23:26:43

标签: python python-3.x while-loop

##---Initializing Variable----------------------------------------------------------------------#
#-----------------------------------------------------------------------------------------------#
monthlyIncome=0
monthlyExpenses=0
totalExpenses=0

##---Introductory Statement: Welcome to the Program---------------------------------------------#
#-----------------------------------------------------------------------------------------------#
def intro():
    print("\n".join(["---------------------------------------------------------",
              "Hello and Welcome to the Budget Analyzer",
              "Get ready to find out how much money you'll have left $$$",
              "---------------------------------------------------------"]))
    return

##---The monthlyIncome mod. gets user input for income/mth to compare against expenses----------#
#-----------------------------------------------------------------------------------------------#
def getIncome(): 
    monthlyIncome=float(input("Please enter the amount of money you'll have for the month: "))
    return monthlyIncome

编辑:我能够让它完成循环,但现在代码一直在询问“输入费用”,无论按下哪个按钮。

如果需要完整代码,请预先输入以下代码序列:

#---Run main module-----------------------------------------------------------------------------#
def main():
    intro()
    getIncome()
    getExpenses(monthlyIncome)

这是主要模块 - 我仍在尝试调试问题所在,所以我还没有完成部分程序:

cairo_pdf

1 个答案:

答案 0 :(得分:1)

您的代码有效,但可能不符合您的预期:

def getExpenses():
    userExpense = 0
    totalExpenses = 0
    moreExpenses = ""
    while moreExpenses != "y":
        userExpense = float(input("Enter an expense: "))
        totalExpenses = totalExpenses + userExpense
        moreExpenses = input("Do you have more expenses? Type y" +\
                             " to input more expenses, or any key for no: ")

    return totalExpenses

要停止循环,请按" y"。

就此而言,它完全符合它在锡上的说法。 但是,这有点不合逻辑:

系统会提示您问题" do you have more expenses"

如果您回答" y" (=是)它会停止...因此您应该将!=更改为=并在循环前将moreExpenses变量预设为y

def getExpenses():
    userExpense = 0
    totalExpenses = 0
    moreExpenses = "y"
    while moreExpenses == "y":
        userExpense = float(input("Enter an expense: "))
        totalExpenses = totalExpenses + userExpense
        moreExpenses = input("Do you have more expenses? Type y" +\
                             " to input more expenses, or any key for no: ")

    return totalExpenses