2016-08-01 6 views
-1

私はこの関数を書いています。文字列の単語数を数えますか?

# Function to count words in a string. 
def word_count(string): 
    tokens = string.split() 
    n_tokens = len(tokens) 
    print (n_tokens) 

# Test the code. 
print(word_count("Hello World!")) 
print(word_count("The quick brown fox jumped over the lazy dog.")) 

が、出力だけではなく、

2 
9 
+3

戻りn_tokensではなく – pawelty

+1

あなたが機能であなたの結果を印刷し、しかし、あなたがいないので、それはNoneを返し、それを印刷そこから何かを返す –

+0

イブそれを修正しました。挨拶:) –

答えて

1

word_count

2 
None 
9 
None 

ではreturn声明を持っていないので、それは暗黙的にNoneを返します。あなたの関数はトークン数print (n_tokens)を出力し、関数呼び出しprint(word_count("Hello World!"))Noneを出力します。

0

別にブライアンが言ったことから、このコードは、あなたが欲しいものを手に入れる方法を示しています。

# Function to count words in a string. 
def word_count(string): 
    tokens = string.split() 
    n_tokens = len(tokens) 
    return n_tokens  # <-- here is the difference 

print(word_count("Hello World!")) 
print(word_count("The quick brown fox jumped over the lazy dog.")) 
関連する問題