Help solving a task🙏

Hi everyone! Im very much of a beginner and I’m trying to solve a problem.

sentence = input('wright a sentence here: ')
res = len(sentence.split())
print(‘You wrote ’ + str(res) + ’ words’)

So far so good. I get the program to tell me how many words i wrote. But now I want the program to tell me the first and the last word in the sentence. Ive tried so many things but just feel stupid.

Wouldnt "print (‘The first word is’ + str(sentence[0]) " work?

It may help to split your code up into individual steps. After calling input(), you get back a sentence - great! But then you do two steps at once: you split the sentence and count the length, all at once. Try doing that in two steps, giving a name to the intermediate result, and possibly printing that out (note that you can print(x) for any x and Python will give you a good look at what it is), and that might give you a great clue as to how to get the first/last words.

No need to feel stupid; you just need to know how to access a list object, is all:

# this puts all the words into a list object right away
sentence = input('Wright a sentence here: ').split()

print(f"Your sentence has {len(sentence)} words.") # how many words
print(f"The first word is {sentence[0]}") # zero is first element of a list
print(f"The last word is {sentence[-1]}") # -1 is the last element of a list

Thank you so much guys, ill try that!

kind regards / Kristoffer

As an FYI, this is an example of how any indexed object (of which a list object is an example) can be accessed:

 position:   |  0  |  1 |  2  |  3  |  4  |
 data:       |  a  |  b |  c  |  d  |  e  |
- position:  | -5  | -4 | -3  | -2  | -1  |

For the above, the object could be a list:
list_data = ['a', 'b', 'c', 'd', 'e']
… or a string…
string = 'abcde'
… to name but two.

Do you see a variable in the program, that contains all the words of the sentence? (Hint: where the code says res = len(sentence.split()), what does this mean, step by step? The purpose of len is to find the length of something, right? What is that “something” in this code?)

Well, did you try it? What happened when you tried it?

As a side note, Python offers a lot of powerful ways to put strings together. It’s not necessary to make every piece into a separate string and + them together. See these links: