Dictionaries and Frequency tables. why is "=" required?

My Code:
content_ratings = {‘4+’: 4433, ‘12+’: 1155, ‘9+’: 987, ‘17+’: 622}
total_number_of_apps = 7197

for row in content_ratings:
content_ratings[row]/ total_number_of_apps
content_ratings[row] * 100

percentage_17_plus = content_ratings[‘17+’]
percentage_15_allowed = content_ratings[‘4+’] + content_ratings[‘9+’] + content_ratings[‘12+’]

Answer code:
content_ratings = {'4+': 4433, '12+': 1155, '9+': 987, '17+': 622}
total_number_of_apps = 7197
for rating in content_ratings:
    content_ratings[rating] /= total_number_of_apps
    content_ratings[rating] *= 100
    
percentage_17_plus = content_ratings['17+']
percentage_15_allowed = content_ratings['4+'] + content_ratings['9+'] + content_ratings['12+']

why do you need the “=” in this part of the code?
content_ratings[rating] /= total_number_of_apps
content_ratings[rating] *= 100

total_number_of_apps is variable with value 7197 already.
Other times python does not seem to use “=” when doing a calculation
eg
var_a = 1000
var_b = 10
var_c = var_a/var_b
python calculates var_c correctly as 100.

@william.tp.lam

Hey,

why do you need the “=” in this part of the code?
content_ratings[rating] /= total_number_of_apps
content_ratings[rating] *= 100

This simply means

content_ratings[rating] = content_ratings[rating] / total_number_of_apps
content_ratings[rating] = content_ratings[rating]*100

So when we want to assign result back to same variable we use this operators +=, *= , /=, etc…

Your code won’t work because you have to assign the result to something after the operation.

Like this,

But when we want to assign result to same variable we can use this operator +=, *=, /=, -= as a short cut.

For example,

Here if you want to assign the result back to var_a instead of var_c, then we can use /= operator.

var_a /= var_b
which simply means,
var_a = var_a / var_b
2 Likes

To update a variable and assign back to value to the variable.

1 Like