【问题标题】:Getting the same range value in a function在函数中获取相同的范围值
【发布时间】:2016-11-28 12:49:03
【问题描述】:

我一直在尝试完成我的作业,但遇到了逻辑错误。我使用的是 Python 3。

print("Car Service Cost")
def main():
    loan=int(input("What is your loan cost?:\t"))
    maintenance=int(input("What is your maintenance cost?:\t"))
    total= loan + maintenance
    for rank in range(1,10000000):
         print("Total cost of Customer #",rank, "is:\t", total)
         checker()
def checker():
    choice=input("Do you want to proceed with the next customer?(Y/N):\t")
    if choice not in ["y","Y","n","N"]:
         print("Invalid Choice!")
    else:
         main()
main()

我得到了这个输出:

Car Service Cost
What is your loan cost?:    45
What is your maintenance cost?: 50
Total cost of Customer # 1 is:   95
Do you want to proceed with the next customer?(Y/N):    y
What is your loan cost?:    70
What is your maintenance cost?: 12
Total cost of Customer # 1 is:   82
Do you want to proceed with the next customer?(Y/N):    y
What is your loan cost?:    45
What is your maintenance cost?: 74
Total cost of Customer # 1 is:   119
Do you want to proceed with the next customer?(Y/N): here

我的排名每次都是 1。我做错了什么?

【问题讨论】:

  • main calls checker 进入循环,调用 main --> 你根本没有循环,只是在每个 first 迭代中重新启动 main循环(你迟早会用完递归深度)。

标签: python python-3.x for-loop range


【解决方案1】:

您不应该在checker 中再次调用main()。你可以直接返回(如果你把它放在一个循环中,你也可以使用break):

def checker():
    while True:
        choice=input("Do you want to proceed with the next customer?(Y/N):\t")
        if choice not in ["y","Y","n","N"]:
            print("Invalid Choice!")
        else:
            return

如果你想跳出main中的循环,如果输入了'n''N',那么你可以尝试返回一个值:

def checker():
    while True:
        choice=input("Do you want to proceed with the next customer?(Y/N):\t")
        if choice not in ["y","Y","n","N"]:
            print("Invalid Choice!")
        else:
            return choice.lower()

然后检查main中是'y'还是'n'

编辑: 如果您不想使用return,您可以只取出循环和else,但这样您将无法检查用户是否想停止:

def checker():
    choice=input("Do you want to proceed with the next customer?(Y/N):\t")
    if choice not in ["y","Y","n","N"]:
        print("Invalid Choice!")

【讨论】:

    【解决方案2】:

    您没有使用for 循环。从checker(),您再次致电main()

    代替

    else: main()
    

    你应该只是return


    我不确定您是否按照checker() 中的意图进行操作。

    【讨论】:

    • 我们还没有学会返回函数,我们被告知我们不应该使用它。谢谢
    猜你喜欢
    • 1970-01-01
    • 2015-02-14
    • 2015-07-25
    • 2019-06-21
    • 2020-11-16
    • 2019-11-11
    • 1970-01-01
    • 2021-10-17
    • 2021-09-12
    相关资源
    最近更新 更多