+ 1
I wrote a code to take a string of words as input and output the number of words there is as integer
#Here is the code. #it says; no output. name = str(input()) n = name.split() def count_word(): word = 0 for words in name: if words == word: word += 1 return word print(count_word()) #where is my mistake?
4 Respostas
+ 1
The easiest way to solve the task of counting words separeted by spaces will be i.e.:
def count_word():
name = str(input())
n = name.split(' ')
return len(n)
print(count_word())
+ 3
Kabir Isyaka what are you are trying to do here "words==word"
Suppose I enter hello world ,it will compare hello with 0 and then world with 0,is that what you want 🤔
Also return stop's further execution of function ,be careful about where to place it
+ 2
This will check 1st word and number 1
Then 2nd word and number 2
you should have 2 for statements.
one that checks for each word and second that is for each number
+ 1
Kabir Isyaka
According to your specification, you don't need if condition there.. Match Identation of return with out of loop.. You are getting none because if condition never true so return which is inside if statement also not executing..
Next if take string in loop as iterable, you get number of characters.
If you take splitted list you will get number of words that is list size.