-4
def eCount (s):

    """Count the e's in a string, using for loop.

    Params: s (string)
    Returns: (int) #e in s, either lowercase or uppercase
    """

    # INSERT YOUR CODE HERE, replacing 'pass'

The professor asks not to change anything above. I'm trying to accomplish:

count = 0
for e in s:
    count +=1
return count

It gives:

(executing lines 1 to 17 of "e_count_103.py")

15
idjaw
  • 25,487
  • 7
  • 64
  • 83
Mengchen Ding
  • 63
  • 2
  • 11

2 Answers2

3

you can try count() like: return s.lower().count('e')

In python 3:

def eCount(s):
    return s.lower().count('e')
s = "helloEeeeeE"
print(eCount(s))

Output:

7

You can either lowercase the string or uppercase it's up to you. (For upper case you can use s.upper().count('E')).For detail read String count() tutorial.

Or if you want to use for loop then try this ( in python 3):

def eCount(s):
    count = 0
    s = s.lower()
    for i in s:
        if i == 'e':
            count+=1
    return count
s = "helloEeeeeE"
print(eCount(s))

It gives same output:

7

Note : e you used in your code in this statement : for e in s: is not character 'e' but variable e so it iterate number of characters in the string and every time incrementing the count variable.

You can also use list comprehension :

def eCount(s):
    return sum([1 for i in s if i == 'e' or i == 'E'])
s = "helloEeeeeE"
print(eCount(s))

For details about list comprehension you can check this Python - emulate sum() using list comprehension.

Community
  • 1
  • 1
Kalpesh Dusane
  • 1,477
  • 3
  • 20
  • 27
1

Using for loop:

def eCount(s):
    count = 0
    for c in s:
        if c in ('e', 'E'):
            count += 1
    return count
acw1668
  • 40,144
  • 5
  • 22
  • 34