-1

I am trying to write a program that inputs a sentence from the keyboard, word by word, into a list. The program should output the following.

  1. The complete sentence, with the first word capitalized if it wasnt already, spaces between each word, and a period at the end.

  2. The count of the number of words in the sentence.

For instance, if the input is:

the

cat

ran 

home

quickly

Your program should output:

The cat ran home quickly. There are 5 words in the sentence.

listMessage = []

message = input('Enter first word of your message: ')

while message != 'done!':
        listMessage.append(message)
        message = input('Please enter the next word of your message or type done! when complete ')
return listMessage
Nilay Singh
  • 2,201
  • 6
  • 31
  • 61
Scott Mc
  • 1
  • 2

4 Answers4

2

Given that you already have listMessage, you can simply:

' '.join(listMessage).capitalize() + '.'
josoler
  • 1,393
  • 9
  • 15
1
def function():

    listMessage = []
    message = input('Enter first word of your message: ').strip()

    while message != 'done!':
        listMessage.append(message)
        message = input('Please enter the next word of your message or type done! when complete ')

    text = ' '.join(listMessage).capitalize()+'.'

    return text
Amine Messaoudi
  • 2,141
  • 2
  • 20
  • 37
1

You've got a couple things you might want to check here, according to your problem description.

If you want spaces between each word, you'll likely want to check to make sure that the words themselves, when entered, don't have leading or trailing spaces already. Use .strip() on your input to ensure this is the case.

If you want to capitalize the first letter of your sentence, you can check to see if listMessage[0][0].isupper() == True. This checks the first letter of the first word for capitalization.

If you'd like to add spaces to each string when you concatenate it, you can try a ranged for loop:

finalStr = ""
for str in listMessage:
  finalStr += (str + " ")

(This will leave a space at the end, remember to .strip() it.)

Put it all together, and you've got your code. Try a working solution here!

Nick Reed
  • 4,989
  • 4
  • 17
  • 37
0

You can try this:

word = ""
sentence = ""

while True:
    word = input("Enter a word: ")
    if word == 'done!':
        break

    sentence = sentence + word + " "

print(sentence)
Paolo Mossini
  • 1,064
  • 2
  • 15
  • 23