Strings and Functions

Hi everyone,

I am quite confused when using functions with strings. Sometimes I need to set an input in a different variable (example 1) for the function to work, and others I just write the input directly within the function (example 2). Why?

Example 1

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

word = "codecademy"
length = get_length(word)

Example 2

def letter_check(word, letter):
  for character in word:
    if character == letter:
      return True
  return False

print(letter_check("strawberry", "a"))
print(letter_check("strawberry", "o"))


Do you mean the counter variable? If so it is because it is needed for some time. In your example, when counting the length of the word "codecademy", you need the variable to exist for the entire time you are counting the letters.

"c" counter is 1.
"o" counter becomes 2.

And so on. Therefore you need the a variable to store the data. In the second example, the program only has to work until it finds the letter in word. Therefore there is not as much data that needs storing; it is yes or no, or in binary, 1 or 0. Therefore it does not need a variable.
I hope this helps.

Write the word on paper. Now count the letters using your pencil. That’s what the first function does.

Now pick a letter, then use your pencil to step through the word. If you find that letter, stop checking. That’s what the second function does.

Thanks for your answer. I get why the counter variable is needed, but I am unable to call the function without stating the variable with the string “word = "codecademy”. Is there a way to call the function say, get_length(codecademy), (similar to the second example) and will also return the counted letters? I tried, but I think I was unable to figure it out.

Thanks for your reply. Yes, I have clear what both functions do. My question was more related to the syntax, where in the first example I need the following to call the function:

word = "codecademy"
length = get_length(word)

and on the second example I only need

print(letter_check("strawberry", "a"))

Is there a way to do one line in the first example?

Yes. However, when you call the function, you need to call it on a string, like this:

 return stuff + "hi"

Is that what you mean?

Bottom line, we can use a good lot of functionality without ever needing global variables, especially if all we want is to see the result or include it in a computation and discard it. A function call IS a value. We can express it the same as any number or string, or list or dict.

1 Like