递归第二次不起作用。 -蟒蛇

时间:2018-11-22 16:09:26

标签: python-3.x python-2.7 recursion multiple-return-values

def twothousand(amt):
    n=500
    div1=amt//n
    mod1=amt%n
    return (mod1,n,div1)


def fivehundred(amt):
    n=200
    div1=amt//n
    mod1=amt%n
    return (mod1,n,div1)


def calculate(amt):
    if amt <10:
        print("hi")

    elif amt>=200 and amt<500:
        mod1,n,div1=fivehundred(amt)
        return (mod1,n,div1)

        #the above return statement isn't returning anything. 
        #That is, now the program doesn't go to the main function 2nd time.

    elif amt>=500 and amt<2000:
        mod1,n,div1=twothousand(amt)
        return (mod1,n,div1)


def main1():
    amt=int(input("Enter the amount: "))
    mod1,n,div1=calculate(amt)
    print (mod1,n,div1)
    #The above print function executes only once.
    if mod1!=0:
        amt=mod1
        calculate(amt)


if __name__=="__main__":
    main1()

输出:

Enter the amount: 1700
200 500 3

期望的输出:

Enter the amount: 1700
200 500 3
0 200 1

如注释中所述,第二次调用calculate()函数后,我无法执行return语句。 我没有得到第二个输出。 python新手,请帮忙。

很抱歉没有更早地更新逻辑。 逻辑是:

当用户要求1700的金额时,只能使用500和200货币给他该金额。因此,第一个输出是-200 500 3;即3个数字为500货币..其余为200。 我想调用该函数,直到值mod1 ==0。

1 个答案:

答案 0 :(得分:0)

您的main()函数应如下所示:

def main1():
    amt=int(input("Enter the amount: "))
    mod1,n,div1=calculate(amt)
    print (mod1,n,div1)
    #The above print function executes only once.
    if mod1!=0:
        amt=mod1
        mod1,n,div1 = calculate(amt)
        print (mod1,n,div1)
相关问题