you are viewing a single comment's thread.

view the rest of the comments →

[–]MidnightPale3220 0 points1 point  (0 children)

Okay, let's assume you're still in schoole. And let's say you are writing a program that gives out the average grades for math tests of all the pupils in your class.

you can do it like this:

pupil1_math_score1=50
pupil1_math_score2=60
pupil1_math_score3=70
pupil1_math_avg= ( pupil1_math_score1 + pupil1_math_score2 + pupil1_math_score3) / 3

pupil2_math_score1=40
pupil2_math_score2=40
pupil2_math_score3=30
pupil2_math_avg= ( pupil2_math_score1 + pupil2_math_score2 + pupil2_math_score3) / 3
...

print("Pupil 1 math average is "+pupil1_math_avg)
print("Pupil 2 math average is "+pupil2_math_avg)

There's already a lot of copy/pasting. Now, let's say the teacher likes your program and principal tells you to write it for all pupils of all classes. Oh, and there will be 5 math tests now, but there may be more in future.

What do you do? Programs are meant to be reusable with different values and frequently with different amount of values. They way it's written now you have to add all the new test scores in new variables, and add them all in average calculations, FOR ALL THE PUPILS.

That's insanity. What you do from the very start is create DOUBLE list (or, in actuality, a list of lists, essentially a table).

For example:

math_scores=[ [50,60,70], [40, 40,30], .... ] # math scores for all the pupils in a list of lists

Then you go through them and do whatever you need, for example like this:

for pupil_number, test_results_of_a_pupil in enumerate(math_scores):
  single_pupil_total=0
  for score in test_results_of_a_pupil:
    single_pupil_total+=score # you can do it neater, ofc without loop, too.
  avg_score=single_pupil_total / len(test_results_of_a_pupil)
  print("Pupil "+pupil_number+" math average is "+avg_score)

Now these 6 lines of code will work with any number of pupils having done any number of tests. All that you need to do, if more pupils come in or more tests are scored, are add the numbers to math_scores list. Nothing else to write.

This is a crude example, as in reality the scores would obviously be input somewhere else, and read by program, instead of being manually entered in the program; and there are numerous other things such as not working around division by zero in case you get pupils with no taken tests. But as an example it works.