2016-12-26 54 views
-2

试图在MIT OpenCourseware Sc 6.00上尝试提问。 问题在于如何找到McNuggets与6,9,20包的组合,并给出总数。 目前我的代码是:TypeError:'NoneType'对象不可迭代MIT Opencourse Assignment

def Mac(): 
    totalnumber = int (input('Enter total number of McNuggets')) 
    num20,num6,num9= solve2(totalnumber) 

def solve2(numtotal): #define a new function to find and print multiple answers 
    solutionfound = False # set up a variable to check if the solution is found 
    for num20 in range (0,numtotal//20 + 1): 
     for num9 in range (0,numtotal//9 +1): 
      num6 = (numtotal-num20*20-num9*9)//6 
      if num6 > 0: 
       checknum = num20*20+num9*9+num6*6 
       if checknum == numtotal: 
        print ('The number of 6-pack is', num6) 
        print ('The number of 9-pack is', num9) 
        print ('The number of 20-pack is', num20) 
        solutionfound = True # change the initial variable to True 
    if not solutionfound: 
     print ('There is no solution') 

但是,运行这段代码时,它总是显示:

TypeError: 'NoneType' object is not iterable

+0

你的代码中哪行引发异常? – elethan

+1

'solve2'返回'None',python试图解压缩它。 – TheClonerx

+0

@Nurzhan不建议在编辑中修改Python代码中的空格。 – MYGz

回答

1

功能solve2()不返回任何值,所以它的返回值是None和你正在尝试通过执行num20,num6,num9= solve2(totalnumber)来重复此操作。所以你的代码的这部分提高了TypeError: 'NoneType' object is not iterable

看着你的代码,我无法决定从哪里返回值,所以无论你想返回值,只需使用return即可。

1

你可以试试这个:

def Mac(): 
    totalnumber = int (input('Enter total number of McNuggets: ')) 
    num20,num6,num9 = solve2(totalnumber) 

def solve2(numtotal): #define a new function to find and print multiple answers 
    solutionfound = False # set up a variable to check if the solution is found 
    for num20 in range (0,numtotal//20 + 1): 
     for num9 in range (0,numtotal//9 +1): 
      num6 = (numtotal-num20*20-num9*9)//6 
      if num6 > 0: 
       checknum = num20*20+num9*9+num6*6 
       if checknum == numtotal: 
        print ('The number of 6-pack is', num6) 
        print ('The number of 9-pack is', num9) 
        print ('The number of 20-pack is', num20) 
        solutionfound = True # change the initial variable to True 
        return (num6, num9, num20) 
    if not solutionfound: 
     print ('There is no solution') 
     return (None, None, None) 

Mac() 

由于这是正确地指出,你需要从你的方法solve2返回值。