-3

This is my first post and I would be happy if someone could please explain to me why we need the result = "" section in the following Python code.

It is a basic piece of code that turns a phrase such as World Wide Web into WWW.

def initials(phrase): words = phrase.split() result = "" for word in words: result += word[0].upper() return result 
7

3 Answers 3

3

+= in result += word[0].upper() implies you're trying to add a character to an existing string, if that existing string isn't pre-defined, it will throw an error.

It can also be written as follows:

result = result + word[0].upper()

Also be curious, try running the code with that portion commented out. Sticks better when you experience it yourself.

Sign up to request clarification or add additional context in comments.

Comments

2

The result needs to be initialised because you're adding something to it every iteration of the loop. Consider this bit:

for word in words: result += word[0].upper() 

The += operator takes result, adds something on, and assigns it back to result. So in your example what's happening every loop is:

# Before loop 1 result = "" # After loop 1 result = "W" # After loop 2 result = "WW" 

If you don't initialise result, then the += operator makes so sense on the first iteration.

Comments

2

It's acting as a temporary container for the strings. Here's a version without the result variable.

def initials(phrase): words = phrase.split() return "".join([word[0].upper() for word in words]) 

1 Comment

Please use code fences (```) to mark your source code, so that it will be formatted appropriately. Otherwise, it will all appear in one long line. Another user fixed this for you.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.