Defining intermediate variables to assign values: is it necessary?

Hi there! I’ll ask my question starting from an example:

Screen Link:

My Code:

content_ratings = {'4+': 4433, '12+': 1155, '9+': 987, '17+': 622}
total_number_of_apps = 7197

c_ratings_proportions = {}
c_ratings_percentages = {}

for item in content_ratings:
    c_ratings_proportions[item] = content_ratings[item]/total_number_of_apps
    c_ratings_percentages[item] = c_ratings_proportions[item]*100

The code provided in the answer:

content_ratings = {'4+': 4433, '12+': 1155, '9+': 987, '17+': 622}
total_number_of_apps = 7197

c_ratings_proportions = {}
for key in content_ratings:
    proportion = content_ratings[key] / total_number_of_apps    
    c_ratings_proportions[key] = proportion

c_ratings_percentages = {}
for key in c_ratings_proportions:
    percentage = c_ratings_proportions[key] * 100
    c_ratings_percentages[key] = percentage

I notice that in the course they always tend to assign values to new variables and then assign those variables to a final destination, like with “proportion” and “percentage” in the solution proposed above.
I tend to skip defining those variables and assign directly the expression where I need it to be.
I understand that the result is the same but my question is: is introducing these variables a good habit I should take, and if so, why? Are there circumstances in which it can be convenient? Is it generally appreciated, or is it better to have shorter code and eliminate intermediate variables? I’m just a beginner and I do not want to form bad habits.

Thanks to everyone!

1 Like

The zen of Python says, Simple is better than complex, Complex is better than complicated .

That being said, it’s not really necessary to use intermediate variables. It can be convenient, when you feel a single code is doing too much of work, try breaking it into segments. But a good habit to build on from early is, always give descriptive names to variables, makes it a lot more easier to understand to others as well as you.

2 Likes

Thank you very much, your answer was clear and useful. And I really like the zen of Python! I’ll take care of choosing names wisely from now on.

1 Like

There’s more such things in the zen of Python. In command prompt, type import this after running python.

2 Likes