我对编程非常陌生。这可以接受吗?

时间:2014-04-19 00:46:48

标签: python function

使用这样的函数是否可以接受?我不确定我是否正确地做到了。这是将值传递给数组的正确方法吗?

def calculateTuitionIncrease(cost, increase, years):  
    counter = 1  
    costsPerYear = []  
    while counter <= years:  
        cost = (cost)+(cost*increase)  
        costsPerYear.append(cost)   
        counter = counter + 1  
    return costsPerYear

def calculateTotalCost(terms,tuition,creditHours,books,roomAndBoard,scholarships):  
    totalBookCost = (books*terms)  
    totalRoomAndBoard =(roomAndBoard*terms)  
    totalCost = (totalBookCost+tuition+totalRoomAndBoard)-(scholarships)  
    return totalCost

使用函数让用户退出程序还是有更好的方法可以吗?

def exitProgram():  
    quitProgram = str(raw_input("Would you like to exit the program (y,n)"))  
    while quitProgram != "y" and quitProgram != "n":  
        quitProgram = str(raw_input("Type 'y' if you would like to exit the program and 'n' if you would like to run it again."))  
    return quitProgram


def main():
    endProgram = "n"
    while endProgram == "n":

        #Variable declaration/initialization
        years = 0
        terms = 0
        numberOfSchools = 0

        tuitionCost1 = 0
        tuitionCost2 = 0
        tuitionCost3 = 0
        tuitionCost = 0

        bookCost = 0
        roomAndBoard = 0
        scholarships = 0

        tuitionIncrease = 0
        adjustedTuitions = 0
        sumOfTuitionCosts = 0
        averageTuitionCost = 0
        totalTuitionCost = 0

        creditHours = 0
        overallCost = 0

        #User inputs
        years = int(input("Will you be going to school for 2, 4 or 6 years?"))

        while years != 2 and years != 4 and years !=6: #Input validation for years.
            years = int(input("Please try again. Do you plan on going to school for 2, 4 or 6 years?"))

        #If-statements for if the user will be attending multiple schools.
        if years == 4 or years == 6:
            numberOfSchools = int(input("How many schools do you plan on attending during this time?"))

        if numberOfSchools == 2:
            tuitionCost1 = int(input("How much will you be paying per credit hour at the first school you'll be attending?"))
            tuitionCost2 = int(input("How much will you be paying per credit hour at the second school you'll be attending?"))
            tuitionCost = (tuitionCost1+tuitionCost2)/(2) #Finds average tuition between schools & assigns it to a variable

        elif numberOfSchools == 3:
            tuitionCost1 = int(input("How much will you be paying per credit hour at the first school you'll be attending?"))
            tuitionCost2 = int(input("How much will you be paying per credit hour at the second school you'll be attending?"))
            tuitionCost3 = int(input("How much will you be paying per credit hour at the third school you'll be attending?"))
            tuitionCost = (tuitionCost1+tuitionCost2+tuitionCost3)/(3) #Finds average tuition cost between schools & assigns it to a variable

        else:
            tuitionCost = int(input("Please enter how much you will be paying per credit hour."))

        terms = (years*2)

        #User inputs
        tuitionIncrease = float(input("Please enter the projected tuition increase per year in percentage form (ex. if increase is 7% enter .07)."))
        creditHours = int(input("On average, how many credit hours will you be receiving per term?"))
        roomAndBoard = int(input("Please enter what your price of room and board will be per term."))
        bookCost = int(input("Please enter what your average book cost will be per term."))
        scholarships = int(input("Please enter the total amount you will be recieving from grants and scholarships."))

        #Calls function that calculates tuition increase per year
        adjustedTuitions = calculateTuitionIncrease(tuitionCost, tuitionIncrease, years)

        sumOfTuitionCosts = sum(adjustedTuitions)
        averageTuitionCost = (sumOfTuitionCosts/years) #Average cost of tuition between all schools including the projected tuition increase.
        totalTuitionCost = (averageTuitionCost* creditHours)*(terms) #Calculates total cost of JUST tuition.

        #Calls function that calculates the total cost of all expenses.
        overallCost = calculateTotalCost(terms,totalTuitionCost,creditHours,bookCost,roomAndBoard,scholarships)


        if numberOfSchools ==2 or numberOfSchools ==3:  #Average tuition rate is only displayed if the user is attending more than 1 college.
            print("The average tuition cost per credit hour between the schools you'll be attending, including the projected tuition increase is", round(averageTuitionCost, 2))

        print ("The total estimated cost for your tuition alone is",round(totalTuitionCost, 2)) #total cost of TUITION ONLY.
        print ("Your total estimated college cost with all expenses is", round(overallCost, 2)) #cost for ALL expenses.

        endProgram = exitProgram()#Calls function that lets user choose to end program

main()

1 个答案:

答案 0 :(得分:1)

这里似乎你有两个不相关的问题。

首先,您的calculateTutitionIncrease函数是否能够正确创建成本值列表。

确切地说,这并不坏,但可能会更好。首先,您可以在for上使用range循环,而不是while循环测试手动递增的整数。当你想要从其他一些序列(比如年数范围)创建项目列表时,更加“Pythonic”的代码风格就是使用列表理解。在这种情况下,这需要稍微不同的数学计算,但结果应该相同:

costs_per_year = [cost * (1+increase)**year for year in range(1, years+1)]

您的第二个问题似乎是您是否应该保留代码以询问用户是否想要退出单独的功能。这是相当主观的,所以确实没有一个正确的答案。我认为有两个很好的理由可以让你将它放在自己的功能中。

首先,它可以帮助您使其他代码更简单,特别是如果大多数其他工作也分离成函数:

def main():
    while True:
        input_data = get_input()
        results = calculate_results(input_data)
        display_results(results)
        if ask_to_exit():
            break

您目前没有看到太多好处,因为您的main功能已经很长很复杂。

第二个原因是您可能想要从其他代码中的多个不同位置调用它。例如,如果你有两个不同的循环,那么使用相同的函数询问用户是否在每个循环中完成它们可能是有意义的。这当然不适用于您的代码,因为您只在一个地方调用exitProgram函数。

所以,最后,这两个原因都不能说明你的情况。这并不一定意味着您应该将exitProgram的内容重新加入main。如果您认为可以更改其他代码(例如,通过将main中的其他步骤分解为自己的函数),将exitProgram作为单独的函数保留可能是有意义的太

进一步的建议:

如果您选择保留exitProgram功能,请选择其他名称。函数通常被赋予名称,这些名称是动词描述它们的作用。你的exitProgram函数有误导性,因为它实际上并没有导致程序退出(它只返回用户想要的,关于退出)。我建议您也返回bool值,而不是调用者需要测试的yn字符串。

此外,Python代码约定是以lower_case_with_underscores格式命名的函数和变量,而不是像您当前使用的那样camelCaseSee PEP 8了解更多Python风格的建议。