Exercise 49

Write a Python algorithm as a function that takes a string and a character as inputs and counts the number of times the character appears in the string without using any predefined functions.


def count_char(string, char):
    count = 0
    for i in range(len(string)):
        if string[i] == char:
            count += 1
    return count

string = "Hello, world!"
char = "o"
result = count_char(string, char)
# This will output 2, since the character "o" appears twice in the string "Hello, world!".

Explanation of how it works:

  1. We define a function called count_char(): that takes two arguments: string and char.
  2. We initialize a variable called count to 0: which will keep track of how many times the character appears in the string.
  3. We use a for loop: to iterate over the indices of the string.
  4. For each index: we check if the character at that index is equal to the character we're looking for. If it is, we increment the count variable by 1.
  5. After the loop is finished: we return the count variable.


Younes Derfoufi

One thought on “Solution Exrcise 49: algorithm python to count the number of times a character appears in string”

Leave a Reply