简体   繁体   中英

Python - None value is being returned from a count

I'm trying to count the max number of spaces there are in a sentence with the following code:

def spaces(sentences):
  textList = sentences.split('. ')
  whiteList = [whitespaces.count(' ') for whitespaces in textList]
  x = max(whiteList)
  print(x)

However, while it is returning the number of whitespaces there are, this is also returning a None on a second line. How come this is the case?

You print the result, but you don't return it. You need to add return x at the end of your code.

You can check this page , which explains the difference between print and return in Python.

You must return a value from your function and then print the result of it

def spaces(sentences):
  textList = sentences.split('. ')
  whiteList = [whitespaces.count(' ') for whitespaces in textList]

  return max(whiteList)

print(spaces(sentences))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM