I was learning about dictionaries in Python and I created a simple program:
# 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.
Using the print commands I get the result:
Dictionary contents:
<‘to’:’two’,’for:’four’>
Length = 2
and when I use the function dixnary, I get the results:
Dictionary contents:
<‘to’:’two’,’for:’four’>
Length = 2
None
Notice the None on the final line. This None gets added when I use the function dixnary. 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.
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()).Or alternatively, have the program return the string, so you can do useful things with it.