【问题标题】:unable to understand the output of this code snippet无法理解此代码段的输出
【发布时间】:2020-05-14 02:52:59
【问题描述】:
i = 1
while (i < 10): 
    i += 1
    print(i),
print(type(i)),
Output 

2
3
4
5
6
7
8
9
10
<class 'int'>

Out[16]: (None,)

当我在最后一行后面加上逗号时,我无法理解为什么我们会在输出中显示 Out[16]: (None,)。

【问题讨论】:

  • 我在运行您的代码时没有Out[16]: (None,)。您能否提供更多代码,或者告诉您使用的是什么 IDE。
  • 解释器将逗号, 关联为tuple 的声明,并且由于print() 函数返回None,您最终得到一个不带括号的元组(None,)

标签: python python-3.x printing while-loop tuples


【解决方案1】:

print(type(i)), 是一个由一个元素组成的元组,例如1,(1,)

print 将返回None,然后将其放入元组中,得到None,,与(None,) 相同

【讨论】:

    【解决方案2】:

    这是因为print() 函数返回None。因此,运行

    print(type(i)),
    

    在你的控制台中相当于运行

    None,
    

    向控制台输出一个元组,即

    (None,)
    

    【讨论】:

      【解决方案3】:

      print 返回None,它不会显示在笔记本中。添加逗号会将None 转换为显示的元组。带有一个元素的元组始终以逗号结尾。

      【讨论】:

        猜你喜欢
        • 2014-03-19
        • 1970-01-01
        • 1970-01-01
        • 2019-10-17
        • 2020-10-21
        • 1970-01-01
        • 2014-09-19
        • 2017-11-13
        • 1970-01-01
        相关资源
        最近更新 更多