TypeError:对于MIT Opencourse Assignment,'NoneType'对象不可迭代

时间:2016-12-26 03:06:51

标签: python

尝试在MIT OpenCourseware Sc 6.00上尝试提问。 问题在于如何找到具有6,9,20包的McNuggets组合,并给出总数。 目前我的代码是:

<?php
$file_data = array_slice(file('file.txt'), 0, 5);
print_r($file_data);

但是,运行此代码时,它始终显示:

  

TypeError:'NoneType'对象不可迭代

2 个答案:

答案 0 :(得分:1)

函数solve2()不会返回任何值,因此其返回值为None,您尝试通过执行num20,num6,num9= solve2(totalnumber)来迭代它。因此,这部分代码会引发TypeError: 'NoneType' object is not iterable

查看您的代码,我无法决定从哪里返回值,因此无论您想要返回值,只需使用return

答案 1 :(得分: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返回值。