user3018867
user3018867

Reputation: 17

Need help writing a Python script that will input a sentence and count the number of words it contains

def main():

  p =input("Enter your sentence: ")

  words = p.split()

  wordCount = len(words)

  print ("The word count is:", wordCount)

main()

I get the read out:

Enter your sentence: Hello world Traceback (most recent call last): File "C:/Python27/idk.py", line 11, in main() File "C:/Python27/idk.py", line 3, in main p =input("Enter your sentence: ") File "", line 1 Hello world ^ SyntaxError: unexpected EOF while parsing What am i doing wrong? D:

Upvotes: 0

Views: 25813

Answers (2)

Sajjan Singh
Sajjan Singh

Reputation: 2553

See the documentation on input. The input function tries to evaluate the given input as a python command.

Try using raw_input instead, which returns the input as a string.

Upvotes: 2

samrap
samrap

Reputation: 5673

You tagged Python 2.7, so I am assuming you are using 2.7. If that is the case, you want to use raw_input() to take string input, not input(). In Python 3, raw_input is replaced by input() function, but in Python 2, the input() function takes input literally, not as a string.

def main():

  p = raw_input("Enter your sentence: ") # raw_input() function

  words = p.split()

  wordCount = len(words)

  print ("The word count is:", wordCount)

main()

Just an addition, if you wanted the input to be an integer, you can still use the raw_input() function. Just int() it! numinput = int(raw_input('Enter a number'))

Upvotes: 1

Related Questions