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
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):
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