[英]Unable to understand results of Python code
I was learning about dictionaries in Python and I created a simple program: 我正在学习Python中的字典,我创建了一个简单的程序:
# Create an empty dictionary called d1
d1 = {}
# Print dictionary and length
def dixnary():
print "Dictionary contents : "
print d1
print "Length = ", len(d1)
# Add items to dictionary
d1["to"] = "two"
d1["for"] = "four"
print "Dictionary contents :"
print d1
print "Length =" , len(d1)
# Print dictionary and length
print dixnary()
Now there's a difference in the results when I use the print
commands and when I use the dixnary
function. 现在,当我使用print
命令和使用dixnary
函数时,结果会有所不同。
Using the print
commands I get the result: 使用print
命令我得到结果:
Dictionary contents: 字典内容:
<'to':'two','for:'four'> < '到': '2', '为:' 4'>
Length = 2 长度= 2
and when I use the function dixnary
, I get the results: 当我使用函数dixnary
,我得到结果:
Dictionary contents: 字典内容:
<'to':'two','for:'four'> < '到': '2', '为:' 4'>
Length = 2 长度= 2
None 没有
Notice the None
on the final line. 注意最后一行的None
。 This None
gets added when I use the function dixnary
. 当我使用函数dixnary
时,会添加此None
。 Why is this? 为什么是这样?
You're attempting to print the return value of a function, but the function doesn't return a value, so it returns the default value of None. 您正在尝试打印函数的返回值,但该函数不返回值,因此它返回默认值None。
The reason why it prints out other data is that you have print commands inside of the function. 它打印出其他数据的原因是你在函数内部有打印命令。 Just run the function ( dixnary()
), instead of printing it ( print dixnary()
). 只需运行函数( dixnary()
),而不是打印它( print dixnary()
)。
Or alternatively, have the program return the string, so you can do useful things with it. 或者,让程序返回字符串,这样你就可以用它做有用的事情。
def dixnary():
return "Dictionary contents :\n%s\nLength = %d" % (d1, len(d1))
print dixnary()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.