I'm pretty new to python. I'm trying to define a function to read from a given file and count the number of words in each line and output the result as a list.
Here's my code:
def nWs(filename):
with open(filename,'r') as f:
k=[]
for line in f:
num_words=0
words=line.split()
num_words +=len(words)
k.append(num_words)
print (k)
print( nWs('random_file.txt') )
The expected output is something like:
[1, 22, 15, 10, 11, 13, 10, 10, 6, 0]
But it returns:
[1, 22, 15, 10, 11, 13, 10, 10, 6, 0]
None
I don't understand why this term None
is returned. There's nothing wrong with the text file, its just random text and I'm only trying to print words in 1 file. So I don't understand this result. Can anyone explain why? And also how can I get rid of this None
term.
I assume the indenting is correct when you tried to run it as it wouldn't run otherwise.
The None is the result of you calling the function in the print statement. Because nWs doesn't return anything, the print statement prints None. You could either call the function without the print statement or instead of using print in the function, use return and then print.
def nWs(filename):
with open(filename,'r') as f:
k=[]
for line in f:
num_words=0
words=line.split()
num_words +=len(words)
k.append(num_words)
print (k)
nWs('random_file.txt')
or
def nWs(filename):
with open(filename,'r') as f:
k=[]
for line in f:
num_words=0
words=line.split()
num_words +=len(words)
k.append(num_words)
return k
print(nWs('random_file.txt'))