I am trying to count the number of occurrences of a specific letter(s) in a string.
To give an example, I want to count the letter a and b in the string "acdjsfdklfdcfnqc"
(String or the specific letters are not important).
Firstly, I defined a container c that will count the occurrences of the letters using a while loop and an if statement. My code is below:
def iterate_through_elements(input_str):
c = 0
for elements in input_str:
if elements == "a":
c += 1
return c
This code worked, here I am only trying to count the number of a's in my string, but when I wanted to count also the b's, I modified my code like above:
def iterate_through_elements(input_str):
c = 0
for elements in input_str:
if elements == "a" or "b":
c += 1
return c
I added an or operator, my idea was to count both the a's and the b's but instead my second function gave me the total number of letters in the string, like the len() function. Then I have managed to accomplish my goal using the function above:
def get_count(inputStr):
num_vowels = 0
for char in inputStr:
if char in "ab":
num_vowels = num_vowels + 1
return num_vowels
My main question is: why my second code from top gave me the total number of letters in the string?
I expected it to iterate through every element and look for if it is a or b, If it was a or b increment the container (variable c) by one. I could not understood how the c was equal to the length of the string and why it worked for a single letter (first function above) and not for the second? What has changed?