有人可以帮助我理解这个Python代码是如何工作的

时间:2013-01-22 12:23:47

标签: python python-3.x

这段代码来自我在学校上课的课程,我对列表的打印方式感到困惑,因为它一直以“无”结尾......

def printlist(myList, pointer):
    print("The List is: ", myList)
    print("Pointer length: ", pointer)
    print("The List length is: ", len(myList))
    print("The List printed properly:")
    print(printlistproperly(myList))

def printlistproperly(myList):
    thelength = len(myList)
    for i in range(thelength):
        print(i, " ", myList[i])

def popin(myList,pointer):
    myList.append(input("Enter a value: "))
    pointer = len(myList)-1
    return myList, pointer

def main():
    myList = ["Ford","Toyota","Mustang"]
    pointer = len(myList)-1
    myList,pointer = popin(myList,pointer)
    printlist(myList, pointer)

结果是:

>>> main()
Enter a value: Dodge
The List is:  ['Ford', 'Toyota', 'Mustang', 'Dodge']
Pointer length:  3
The List length is:  4
The List printed properly:
0   Ford
1   Toyota
2   Mustang
3   Dodge
None

我真正的问题是......最后是什么?它从何而来?我该如何解决?

1 个答案:

答案 0 :(得分:10)

在函数printlist中打印函数printlistproperly的结果,该函数不返回任何内容。因此,您获得了None。解决方案:只需致电printlistproperly(myList)(不使用print)。

def printlist(myList, pointer):
    print("The List is: ", myList)
    print("Pointer length: ", pointer)
    print("The List length is: ", len(myList))
    print("The List printed properly:")
    printlistproperly(myList)