+= python confusion/clarification

Now, instead of printing ‘space!’, use the addition assignment operator to add the space (currently stored in char) to the current value of encrypted_text.

text = ‘Hello World’
shift = 3
alphabet = ‘abcdefghijklmnopqrstuvwxyz’
encrypted_text = ‘’

for char in text.lower():
if char == ’ ':
encrypted_text += char
index = alphabet.find(char)
new_index = index + shift
encrypted_text += alphabet[new_index]
print(‘char:’, char, ‘encrypted text:’, encrypted_text)

I figured the answer out correctly but I’m trying to understand why there’s a difference between:

encrypted_text += char opposed to char += encrypted_text

since it is addition (maybe thinking of it in terms of math is incorrect) wouldn’t both terms be the same? Why do they run different?

I understand why for example shift = 3 works while 3 = shift doesn’t but why would the order matter in this case. I’m just trying to grasp this better before moving on.

Hello there!

Maybe this translation will help.

This encrypted_text += char is the same as this encrypted_text = encrypted_text + char

and

this char += encrypted_text represents this char = char + encrypted_text

Do you notice the differences?

1 Like

Omg yea that makes sense. I completely forgot a = a + b is the same as a += b. I keep thinking of it as strictly math (a + b) and it throws me off sometimes. That actually helped a lot, thanks!

You are very much welcome!