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.
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...
+ 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/
+ 2
Hi Python learner,
Thank you for the detailed explanation and links. The code worked. And I understood the difference between print and return:)
+ 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
0
text = str(input())
letter = str(input())
def letter_count():
print(text.count(letter))
letter_count()