Python help please

So I am trying to count the number of spaces in a sentence
but I am doing something wrong since its giving me the number of letter
1
2
3
4
5
6
7
8
9
10
def countSpaces(sentence,s):
    count = 0
    max = len(sentence)
    wordList = []
    while count < max:
        for s in sentence:
            count += 1
            wordList.append(s)
    
    return count

countSpaces('i love you',' ')
Last edited on
I don't know python but where do you check if s is a space?
Your "while count < max" loop is unnecessary if you're already going to to use a for loop. I would only have the for loop.

Like naraku said, you'd want only increment count if s is a space, since you're trying to count the number of spaces.
i have to use a while loop ( requirment)
I know how to do this using for loop but not while loop
Look up how a for loop processes things. If you have to do it like this, the way I immediately think of is to do one of these solutions, which is literally just transforming a for loop into the appropriate while loop.

Here are solutions for both index-based (i.e. for index in range(len(sentence))) and iterator based (i.e. for c in sentence):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
def countChar (sentence, s):
    """Converting an index-based for loop into a while loop."""
    count = 0
    index = 0
    while index < len(sentence):
        if sentence[index] == s:
            count += 1
        index += 1
    return count

# OR

def countChar (sentence, s):
    """Converting an iterator-based for loop into a while loop."""
    count = 0
    try:
        it = iter(sentence)
        while True:
            c = next(it)
            if c == s:
                count += 1
    except StopIteration:
        return count
Last edited on
Topic archived. No new replies allowed.