【问题标题】:NoneType occuring when I run my code [duplicate]运行代码时发生 NoneType [重复]
【发布时间】:2018-01-27 21:54:30
【问题描述】:

为什么这段代码返回None

 def html_list(inputs_list):
    print("<ul>")

    for html in inputs_list:
        html = ("<li>" + html + "</li>")
        print(html)

    print("</ul>")

bam = ['boom','bust']

print(html_list(bam))

【问题讨论】:

  • 你认为它应该返回什么?为什么?
  • 这就是我正在尝试解决的问题。编写 html_list 函数。该函数接受一个参数,一个字符串列表,并返回一个单独的字符串,它是一个 HTML 列表。例如,如果函数在提供列表 ['first string', 'second string'] 时应生成以下字符串。
    • 第一个字符串
    • 第二个字符串
    即字符串的第一行应该是开始标记
      。接下来是源列表中的每个元素一行,由
    • 标签包围。字符串的最后一行应该是结束标记
    .

标签: python python-3.x nonetype


【解决方案1】:

您的函数中有 print 调用,但没有返回任何内容。如果一个函数完成但没有返回,它真的返回None

这意味着如果你在 print 语句中调用函数,它将运行,在函数中执行 prints,但返回 None,然后将传递给 print() 函数 - 所以这个这就是为什么您会得到预期的输出,然后是 "None"

你也可以通过一个更简单的例子看到这一点:

>>> def f():
...     print("inside f")
... 
>>> print(f())
inside f
None

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多