How does the *= operator work?


How does the *= operator work?


The *= operator takes the value currently stored in the variable on the left and multiplies it by the value on the right, then stores the result back into that variable. It saves us from having to rewrite the name of the variable on the right side of the =, like this:

my_var = 10
my_var *= 10  # 100

longer = 10
longer = longer * 10  # 100

my_var *= 10 is essentially the same as my_var = my_var * 10

my_var = 10
my_var =  my_var * 10 
my_var  *= 10

it multiplys my_var with number 10 in bouth way

A question, take a look on this:

def product(list):
  total = 1  # if 0 then 0, if 2 then 200, and so on...ok
  for num in list: # this is a loop...ok
    total = total * num  # and here...where is this "[4*5*5]", in which part?
  return total 

print product([4, 5, 5])

Ok, I dont get it, how this function knew to multiple like that? Anyone understand my question?

1 Like

I also don’t understand this. Can someone please explain?

1 Like

You set your total = 1. While iterating through list (which is e.g. 4,5,5): first iteration: total = 14 , next iteration: total = (14)5, last iteration total = (14*5)*5.

1 Like

if you print out whats happening, you can sort of see how it works…

  def product(list):
	total = 1
	for num in list:
		total = total*num
	return total


Why can we do this function without using split to take out the values, like in censor?

def censor(text, word):
words = text.split()
result = ‘’
stars = ‘*’ * len(word)
count = 0
for i in words:
if i == word:
words[count] = stars
count += 1
result =’ '.join(words)

And the current one:
def product (integers):
total = 1
for numbers in integers:
total *= numbers
return total

print product([4, 5, 5])

text is a single string, consisting of words separated by spaces. The expression words = text.split() returns a list consisting of the individual words from the string text. The remainder of the function operates on that list, words.

In your second example, the parameter integers is already a list.

why is this whole lesson with 15 HARD AF


This link might help

It helps to add in a bunch of print statements like so:

def product(items_to_multiply):
  total = 1
  print "Loops are about to start, with each loop grabbing only a single list item in items_to_multiply..."
  for num in items_to_multiply:
    print "Start of a loop. Here is the list item for this loop: " + str(num)
    print "This is the total BEFORE we multiply that list item: " + str(total)
    total = total * num
    print "This is the NEW total: " + str(total)
  return total 

product([4, 5, 5])