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
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: