7.3. What is a List?¶
A list holds items in order. A list in Python is enclosed in
] and can have values separated by commas, like
[1,2,3,4,5,6,7,8,9,10]. You probably use lists all the time. People often
make a list before they go shopping or a list of things to do. A list has an order and each list item has a position in the list, like the first item in a list or the last item in a list.
When you ran the code in the last section, did you get 55? That’s the sum of all the numbers from 1 to 10. Here is the program again. Run it if you don’t remember what it printed before.
7.3.1. Using Better Variable Names¶
Let’s write that program again with a better variable name. We will use
product instead of
sum for the variable name that holds the result of the calculation. Step through the code below by clicking on the Forward button and note what value the variable
number is set to each time through the loop. Also note how the variable
product changes during the loop.
The following program calculates the average of a list of numbers, but the code is mixed up. First initialize the sum to 0. Then create the list of numbers. Loop through the list and each time add the current number to the sum. Print the sum divided by the number of items in the list. <b>Don’t forget that you must indent the lines that are repeated in the loop</b>.
Define a function to calculate the sum of 1 to the passed number using the range function. Return the sum from the function. Call the function and print the result.
Discuss topics in this section with classmates.