Can someone please help a beginner with a loop?

Hi everyone,
I am a beginner with coding in general, and learning an online course.
We have a task to use a “for” loop to count spaces (" ") in a given string.
I wrote a code that returns the right answer for one space, but failed to detect two spaces or no spaces (in that case i get an error message: UnboundLocalError: local variable ‘new_cnt’ referenced before assignment).
If someone can explain me please where’s my mistake I would much appreciate it!

My code is (with underlines instead of spaces at the beginnings of the lines) [EDIT - CAM: Fixed it for you]:

cnt = 0
def count_spaces(s):
    for x in s:
        if x == " ":
        new_cnt = cnt+1
    return new_cnt

THANX!

You’re so close; well done.

This is what you’re trying to do:

def count_spaces(s):
    count = 0
    for x in s:
        if x == " ":
            count += 1
    return count

I would have given you ‘pointers’ or ‘hints’, but given how close you are, you’d likely learn more from just having your code corrected.

Wow, that was super fast! Thanks a lot Rob!
Can you please translate me the line “count += 1” to pseudo-code?
As far as I understand it the translation goes “if you add to the count variable - you add 1 each time”.
But I don’t feel 100% sure about my translation.

You’re welcome.

The line count += 1 is called syntactic sugar and means count = count + 1; basically increment count by one, based upon the if x == " ": branch.

Does that make sense?

To put it another way: take the value of count, add 1 to it and reassign the result back to the variable count.

Yes, it helped, I understood my mistakes:
I should’ve been using the “count” command.
I should have placed the count variable inside the def block
I feel like an idiot, but I guess it’s normal when you start programming… :joy:

You’re not an idiot; an idiot would not have come up with your code from the get-go.

Remember: it is better to try, but fail, than not to try at all.

Thanks a lot for the uplifting words mate!

1 Like

For completion, this is a more ‘readable’ way of coding that function:

def count_spaces(string):
    '''
    returns the number of space characters in a given string object
    as a <class 'int'> object
    '''
    space = " "
    space_count = 0
    for char in string:
        if char == space:
            space_count += 1
    return space_count

Notice:

We know have a ‘docstring’, which can be accessed with print(count_spaces.__doc__) or help(count_spaces). Not entirely necessary for a simple function, but it illustrates the point.

We also now have descriptive names for the objects, which makes the code much more ‘human readable’; even for relatively simple scripts, it is easier to see what is going on and as such easier to debug, if needs be.

Just some habits worth getting into as you progress.

Happy coding.

This is matter of definition what is “space”. Is newline a space? It separates characters/words.

>>> s = "a\nb\nc"
>>> len(s)
5
>>> s
'a\nb\nc'
>>> print(s)
a
b
c
>>> count_spaces(s)
0

If any non-printable character is considered space then split-join can be used: compare length of string with length of string with whitespaces removed:

>>> len(s) - len(''.join(s.split()))
2

No, I don’t think so: the two are clearly defined.

A space is 0x20
A newline is 0x0A

agreed “space” is pretty clearly defined, though there is:

In [12]: print("is\N{NO-BREAK SPACE}this a space?")
is this a space?

I"m guessing at the level of this question, plane old space is fine, but if you want whitesapce, then str.isspace() would work:

In [14]: for c in  "is\N{NO-BREAK SPACE}this a space\n?":
    ...:     if c.isspace():
    ...:         print(repr(c), "is a whitespace")
    ...:     else:
    ...:         print(repr(c), "is not whitespace")
    ...: 
'i' is not whitespace
's' is not whitespace
'\xa0' is a whitespace
't' is not whitespace
'h' is not whitespace
'i' is not whitespace
's' is not whitespace
' ' is a whitespace
'a' is not whitespace
' ' is a whitespace
's' is not whitespace
'p' is not whitespace
'a' is not whitespace
'c' is not whitespace
'e' is not whitespace
'\n' is a whitespace
'?' is not whitespace

but now we’re probably confusing things –

NOTE: the split() trick is pretty clever actually :slight_smile:

Final note to OP: if you put your code in tripple back ticks: ```– it will get nicely formatted. (or click the </> button)