繁体   English   中英

为什么我的函数不返回任何内容,而是在交互模式下执行时返回?

[英]Why isn't my function returning anything but is returning when I am executing in interactive mode?

当我以交互模式执行下面提到的代码时,它会提供所需的输出。 但是当我试图通过调用函数来执行它时,它没有返回任何东西。 为什么会发生?

def alt_ele():
    mylist=list(input("Enter the elements: "))
    newlist=[int(i) for i in mylist]
    try:
        for x in range(len(newlist)):
            newlist.pop(0)
            newlist.pop()
    except IndexError:
        pass

您需要为您的function添加一个return语句。 interactive模式下,当functions的输出未分配给变量时,它们会被printed 例如:

>>> 3 + 5        //no variable assignment prints out the result
8

但是,如果您在python文件中有一行3 + 5 ,那么将不会printed 8 ,因为您不再处于interactive模式。

同样的逻辑也适用于function 如果您希望打印从new_listpopped的值,您可以通过修改这些行来直接print它们:

print(new_list.pop(0))
print(new_list.pop())

或者你可以在function的末尾添加一个return语句。

我希望这会有所帮助,但是由于我不知道您想return什么(例如list或只是第一个pop() ),我无法真正帮助return语句!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM