Is this code the best it can be?

Is this code the best it can be? And yes, my variable names are stupid haha.

def add_exclamation(word):
  if len(word) >= 20:
    return word
  new_word = []
  for i in word:
  while (len(new_word) < 20) == True:
  new_new_word = ''.join(new_word)
  return new_new_word

This is my version for this block of code

def add_exclamation(word):
  while len(word) < 20:
    word += "!"
  return word
1 Like

Wow I can’t believe I didn’t think of that. Producing the list was completely unnecessary for me to do, thank you!

No problema! Practice makes perfect. The more you code the more you start thinking of easier ways of doing things.
I’ve been doing this for less than two months but can clearly see my progress- the key is to think like a computer would. According to me

Hey, sorry to chime in a month later but I thought strings were immutable. Can you help me understand how += works on a string?

Is it that I’m just redefining the argument with a concatenation?

Yes. Id of object that variable refers to changes in case of string (and doesn’t in case of list):

The reason why you get to concaténate a string is because you are not actually mutating the object. What Python does here, grabs object “a” + “b” and creates a new string object rather than just modifying the existing one.
In this specific case, the word used as an argument becomes the object in the variable named “word”, then the object gets thrown away and replaced on every iteration creating a new string until the while condition is met.

“ word += ‘!’ “ is short for “word = word + ‘!’”

Hope this helps.


Brilliant, as I suspected :slight_smile: That should streamline some of my more Brobdingnagian .append, .join functions!