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.

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

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

Use only position, consider when the last line should be executed.

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?

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.

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.

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

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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.