For Loop

Description

In Sage, we can create a For Loop which allows for repetition to occur without excessive coding. The For Loop will run through all the values in the range and will go through all the commands that are indentations. In the Sage cell below, the loop will sum the values $0,1,2...9$.

Sage Cell

Code

total=0
for i in range(0,10):
    total=total+i
print total

Options

Instead of giving a range of values to use in our For Loop we can instead use a list. The Sage cell below sums the values $1,2,3,4,$ and $5$.

Code

total=0
for i in [1, 2, 3, 4, 5]:
    total=total+i
print total

Tags

Primary Tags:

Secondary Tags:

Related Cells

None

Attribute

Permalink:

Author:

Date: 13 Nov 2018 16:12

Submitted by: James A Phillips

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