FAQ: Introduction to Strings - Iterating through Strings

This community-built FAQ covers the “Iterating through Strings” exercise from the lesson “Introduction to Strings”.

Paths and Courses
This exercise can be found in the following Codecademy content:

Computer Science

FAQs on the exercise Iterating through Strings

Join the Discussion. Help a fellow learner on their journey.

Ask or answer a question about this exercise by clicking reply (reply) below!

Agree with a comment or answer? Like (like) to up-vote the contribution!

Need broader help or resources? Head here.

Looking for motivation to keep learning? Join our wider discussions.

Learn more about how to use this guide.

Found a bug? Report it!

Have a question about your account or billing? Reach out to our customer support team!

None of the above? Find out where to ask other questions here!

3 posts were split to a new topic: Yet another one incorrect description…

Why does the assignment say “don’t cheat, use len()”, but then the solution offered by the team has no len():

def get_length(word):
counter = 0
for letter in word:
counter += 1
return counter

4 Likes

That comma you’ve accidentally replaced the word ‘and’ there completely changes the sentence!

“Don’t cheat and use len” means don’t use len, your sentence means use len! I don’t know if they’ve changed the wording on the course since you’ve posted.

3 Likes

I don’t understand the counter variable in the following solution, can anyone explain it to me?

def get_length(word):
counter = 0
for letter in word:
counter += 1
return counter

In the example they just used:
def print_each_letter(word):
for letter in word:
print(letter)

Welcome to the forums!

The example doesn’t try to solve the same problem as the lesson instructs you to do. Rather, it simply demonstrates how we can iterate through a string. The example and the solution are completely unrelated.

We want to find the length of a string. The counter variable is used to accomplish this, as we increment it by one for each letter we encounter in the word that is passed to the function. This means that the counter will increase by 1 for each letter in word until there are no more letters. The loop then ends and counter (i.e. the length of the word) is returned.

“The example and the solution are completely unrelated.” ← There’s the big problem. It’s kinda like making an example saying we can measure the circumference of the earth in meters. Then the exercise is to measure the circumference of Mars. The answer is supposed to be in bananas but it was never mentioned in the example of the lesson, and it’s not explained anywhere how and why.

I still don’t understand the solution though - I can guess, but I don’t understand it.

5 Likes

Where’s the problem? When we learn a concept and put it into practice, it doesn’t benefit us if we simply copy a provided solution. Rather, we should apply our newfound knowledge of the concept to a similar, but different, situation in order to effectively learn.

If I were to use your parallel, ifwe were learning to measure the circumference of planets, and were given an example of how to measure the circumference of Earth, it wouldn’t make sense to attempt the same thing ourselves. Rather than repeating and copying the example of measuring Earth’s circumference, we should apply our knowledge to measure the circumference of another planet, like Mars.


What about the solution do you not understand? It might help to post the code that you wrote (and please format it using the </> button).

I tried multiple ways to use len() on a string in the local scope and assign values on the global scope to use on the function scope.

I implemented len(), the result is correct on behalf vscode, COA returns none, Codebyte is returning 4.

def get_length(str1='blue'): if 'blue' in str1: x = len(str1) return x result = get_length() print(result)

def get_length(word):
counter=0
for i in word:
print(i)
counter+=1
return counter

print(get_length(“testString”))

1 Like

Hi -
I just did this problem and was confused too, because I didn’t know that python can recognize the word “letter” to literally mean letter. Until now, we have used this type of phrase " for ___ in ___ : " with an arbitrary name for the variable. This wasn’t clear to me when I read the lesson. Maybe you had the same hang-up?

Python only knows it’s a character, not a letter. We give it the literal name for our reader, not for Python, hence, arbitrary. It only sees the character data it is iterating over.

Oh got it! Thank you for correcting me. I see now that you can still can use arbitrary names to iterate through the string. I played around with the solution using random names. My mind is still boggled but it’s sinking in.

1 Like

Hey Codecademy fam :smiley:
Right to the point, can someone explain to me why the variable “counter” cannot be defined globally (outside of the function) in this example:

counter = 0
def get_length(a_string):
for letter in a_string:
counter += 1
return counter

get_length(“test”)


I get an “UnboundLocalError” when I do perform this action, which explains to me the following:

local variable ‘counter’ referenced before assignment.

I guess I don’t fully grasp the global and local variable concept, can someone please elaborate in simple terms?

The variable needs to be set to 0 each time the function runs. Better to do this inside the function rather than before each and every call to the function.

1 Like

Hi Roy :wave: @mtf
Thanks for your reply! Sincerely, I appreciate your time & you sharing your knowledge :smiley:

Initially my thought process was that defining my variable globally would mean that when I perform a call to my function, “get_length()” that Python would “scan” my program, find the variable it needs to execute my program, ex. counter, and then iterate away.

Would it be more a more correct perspective to assume that variables outside the program are seen and called each time my for loop is executed? and that by placing my variable inside the function body I prevent the counter being “reset” each and every time?

Sorry for the mouthful! If any of ↑ this sounds totally wrong feel free share your perspective. I feel like I may have crossed my wires :confounded: Haha!

Actually, by placing the variable inside the function it gets defined and initialized each time the function runs, as it should. Since the value is returned, we are getting what we need from the variable and can let it die at the end of the function.

One thing we learn in short order is that the less global variables we have, the better. Functions can act as variables that give a value each time they are called. Set this idea aside for the time being and keep up with your lessons, especially with practice of each new concept, along with extra reading of the docs, as you go. Stick with each concept until you are comfortable with it.

1 Like

I hear you @mtf !

That actually makes a lot of sense, and I like the way you explained this concept. It’s clear to me now why in the example code I first provided was acting the way that it was. “…it gets defined and initialized each time the function runs…”.

Taking a step back looking at the big picture, I foresee at the very least a program experiencing performance issues it were to contain a ton of global variables. I’m sure there are more reasons to keep the amount of global variables to a minimum, but I’ll take your advice and leave that for the time being.

Thanks again for all your input Roy.

2 Likes

I am SO confused as to why this is not working!

length = 0 def get_lengthi(example): for x in example: length += 1 return length get_lengthi("Masood")

I get an error UnboundLocalError: local variable ‘length’ referenced before assignment. Can anyone help me out? my variable length was defined right from the start so it should be useable everywhere right?

Your function is making an assignment to an undeclared local variable, not the global one you’ve declared above it. Python does not permit assignment to a global, only a local. It does permit accessing of globals, though.

More importantly, we will want length to be zeroed out at the start of any calls made to the function so move line 1 to just inside the function.

2 Likes