0

Hi, I have just recently started using python and I couldn't figure out two problems regarding finding the first three occurrences of spaces using while loops. I have trouble understanding the concept of while loops.

How would i write a program that reports the first three occurrences of a space, using a while loop. Assume that there will be at least three spaces in the string. Any string with fewer than 3 spaces is considered invalid input, and so the program is allowed to function improperly.

what i tried and got was:

s=raw_input('Enter a string: ')
position=0
while i < len(s):
if s==' ':
position = position + 1
print 'There is a space in position ' + str(position)

Second:

I have modify the previous program so that it does not give an error if there are fewer than three spaces in the string but otherwise behaves the same.

3
Contributors
8
Replies
10
Views
5 Years
Discussion Span
Last Post by pyTony
0

From where is the value of i coming? Push CODE button before pasting your code.

Edited by happygeek: fixed formatting

0

i thought it would be along the lines of:

s=raw_input('enter a string: ')
position=0
while i < len(s):
    if s[i]==' ':
        position = position + 1
print 'There is a space in position ' + str(position)

i used the i for for loops but am really confused about the while loops and how they function

0

It was easier for me with a function, also if you want to get the correct index value remember that python counts the first as 0, so how do you think you should accommodate for that d3fined?

0

okay so i tried to do this question from a different view and i got this:

s = raw_input('Enter a string: ')
i = 0
v = 0
while i < len(s):
    if s[i] == ' ':
        v = v + 1
    if i in range(0, 4):
        print 'There is a space in position ' + str(i)
        i = i + 1

i included the range so it can only count three spaces. but i don't understand why it isn't computing the spaces anymore.

0

You are only accepting space among four first letters (range(4), and i is always zero whem checking for space. Alsothe while loop does not terminate because i does not increase.

0

so do i have to make the i increase in order for it to terminate?

s = raw_input('Enter a string: ')
i = 0
v = 0
while i > len(s):
    if s[i] == ' ':
        v = v + 1
    if i in range(0, 4):
        print 'There is a space in position ' + str(i)
        i = i + 1
0

Remove the line 7 and think again the while condition considering that length of string is never negative. Add more print statements for debuging.

Edited by pyTony: n/a

This article has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.