For Loop Tables


Here, we will use a for loop to generate a table of $f(0)$ to $f(9)$ where

\begin{equation} f(x) = (x - 7)(x - 10) \end{equation}

Sage Cell

We'll run through this line-by-line:

Line 1: Here we just define f(x) like we normally do

Line 2: This starts the loop. i is our index variable. The loop will complete all code in it, add 1 to i until i = 10 and thus exits the range and terminates the loop. 0, 10 is out range, and essentially means the loop will continue while $0 \leq i < 10$, so if you wanted the table to continue to 10, you would change 10 to 11.

Line 3: This is simply a normal print statement, except we end it with a comma. This tells Sage to print the next statement on the same line. Note this line and line 4 are indented to signal to Sage that they are contained in the loop.

Line 4: This is another print statement. We want a new line after this one, so note that it does not end with a comma.


f(x) = (x - 7) * (x - 10)
for i in range (0, 10):
    print (i, f(i))


Arbitrary Lists

Keeping $f(x)$ from the previous cell, say we wanted to specifically print

\begin{align} f(2),\ f(3),\ f(5),\ f(7),\ f(11),\ f(13),\ f(17),\ f(19) \end{align}

There's no way to increment i through these values since they have varying spacing, but we can instead make a list of the x-values we want and iterate through that using a loop:

The loop here works largely the same as the previous one, except that instead of i incrementing by 1 when the loop repeats, it proceeds to the next list value. The loop terminates after it processes the last value in the list. Note that because we provide a list instead of a range, the syntax to begin the loop is for i in values:; the keyword range is not present.


f(x) =(x - 7) * (x - 10)
values = [2, 3, 5, 7, 11, 13, 17, 19]
for i in values:
    print (i, f(i))


Primary Tags:

Secondary Tags:

A list of possible tags can be found at The WeBWorK Open Problem Library. For linear algebra tags see the Curated Courses Project.

Related Cells

Any related cells go here. Provide a link to the page containing the information about the cell.




Date: 10 Mar 2019 17:06

Submitted by: Zane Corbiere

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License