2016-08-01 128 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."))