2

私は 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()

printコマンドを使用したときと関数を使用したときの結果に違いがありdixnaryます。

printコマンドを使用すると、結果が得られます。

辞書の内容:
<'to':'two','for:'four'>
長さ = 2

関数を使用するとdixnary、結果が得られます。

辞書の内容:
<'to':'two','for:'four'>
長さ = 2
なし

None最終行の に注意してください。関数を使用すると、これNoneが追加されますdixnary。どうしてこれなの?

4

1 に答える 1

11

関数の戻り値を出力しようとしていますが、関数は値を返さないため、デフォルト値の None を返します。

他のデータを出力する理由は、関数内に印刷コマンドがあるためです。dixnary()関数を表示する ( ) のではなく、実行するだけです ( print dixnary())。

または、プログラムに文字列を返させて、それを使って便利なことができるようにします。

def dixnary():
    return "Dictionary contents :\n%s\nLength = %d" % (d1, len(d1))

print dixnary()
于 2012-04-24T15:44:15.503 に答える