0

Python “How many letters “

Please kindly teach me the code for practice 42.2 Python ‘how many letters.’ Write a function that takes a string and a letter as its arguments and returns the count of the letter in the string. My understanding is below. def letter_count(text, letter): #your code goes here text = str(input()) letter = str(input()) print(letter_count) It doesn’t work. I also don’t understand the difference between return and print.

3rd Oct 2021, 4:38 AM
YokoS
5 Answers
+ 5
Something like : count = 0 for i in text: if i == letter: count+=1 return count Would be the most obvious solution... (Of course there are way better solutions but that's the most naive one.. ) Regarding difference between return and print... print() is a function that prints some string or values to the screen(console), when return returns a value from the function to where it was called from. Also there is no point in using str() on the input as input() returns string by default... But if you can't do something like that on your own.. Maybe you should consider going through python for beginners course again...
3rd Oct 2021, 4:44 AM
Aleksei Radchenkov
Aleksei Radchenkov - avatar
+ 5
Hi Yokos! Here, your letter_count() function doesn't return anything hence there's no return statement. In Python, there is an in built function called count() to count anything. So, you can use this in the return statement. So, it needs to be like this def letter_count(text, letter): #your code goes here return text.count(letter) text = str(input()) letter = str(input()) print(letter_count(text,letter)) You can refer this article to understand the difference between print and return https://pythonprinciples.com/blog/print-vs-return/
3rd Oct 2021, 6:05 AM
Python Learner
Python Learner - avatar
+ 2
Hi Python learner, Thank you for the detailed explanation and links. The code worked. And I understood the difference between print and return:)
3rd Oct 2021, 7:06 AM
YokoS
+ 2
txt = input() let = input() print (txt.count(let)) First I took text in which we have to find the letter as input using input function and then I took letter in let variable which we have to search in string. After that I just used count method available in PYTHON. If you wants to know how that count works then you can look at Aleksei Radchenkov answer
3rd Oct 2021, 11:41 AM
🌀 Shail Murtaza ŰŽŰčیل Ù…Ű±ŰȘŰ¶ÛŒÙ°
🌀 Shail Murtaza ŰŽŰčیل Ù…Ű±ŰȘŰ¶ÛŒÙ° - avatar
0
text = str(input()) letter = str(input()) def letter_count(): print(text.count(letter)) letter_count()
16th May 2022, 8:55 AM
Junior Jackson
Junior Jackson - avatar