Christian Traylor
Christian Traylor

Reputation: 5

Writing a function to see how many times a character appears in a set of words

To better help understand the fundamentals, my professor asked people in our class to write a function to see how many times a character appears in a set of words. I am having trouble integrating ord() into the function. Also, I understand that there are easier ways of getting the outcome.

Here is what I have so far:

def function(char):
    word = "yes"
    for char in word:
        ord(char)
        return ord(char)

function('y')

I don't get any errors - but I also don't get anything back

Upvotes: 0

Views: 43

Answers (2)

Michael
Michael

Reputation: 426

return will automatically end a function, and not keep it going. there are also a lot of variables that you are not using, like the char parameter you passed to your function. when using the for loop, the variable created after for will be reassigned.
try this:

def function():
    word = 'yes'
    NewList = []
    for char in word:
        NewList.append(ord(char))
    return NewList

print(function())

however what i think would be better:

def function(word):
    NewList = []
    for char in word:
        NewList.append(ord(char))
    return NewList

print(function('blahblah'))

also, when simply calling a function from a file, the returned value is not automatically displayed, you must include a call to print

Upvotes: 0

Ujjwal Gulecha
Ujjwal Gulecha

Reputation: 183

That is because you aren't printing anything! Also, there are issues in your code, first one being the parameter 'char' and the 'char' in the for loop have the same name, that will cause issues.

A small code to find the count of a given letter can be something like this:

def function(word, char):
  count = 0
  for c in word:
    if c == char:
      count = count + 1
  return count

print (function("yes", 'y'))

Upvotes: 1

Related Questions