2016-08-01 155 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 
None 
9 
None 

,而不是僅僅

2 
9 
+3

返回n_tokens – pawelty

+1

您打印結果的功能,但它返回無既然你不從它返回任何東西 –

+0

ive修復它。致敬:) –

回答

1

word_count沒有一個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."))