+ 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?

24th Oct 2020, 4:39 PM
KABIR āš”šŸ‡³šŸ‡¬
KABIR āš”šŸ‡³šŸ‡¬ - avatar
4 Answers
+ 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())
24th Oct 2020, 5:02 PM
JaScript
JaScript - avatar
+ 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
24th Oct 2020, 4:46 PM
Abhay
Abhay - avatar
+ 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
24th Oct 2020, 4:42 PM
Steve Sajeev
Steve Sajeev - avatar
+ 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.
24th Oct 2020, 5:02 PM
Jayakrishna šŸ‡®šŸ‡³