For Loops in SageMath

Math 304: Number Theory - Spring 2026

Introduction to For Loops

For loops allow you to repeat code multiple times, which is essential for solving many mathematical problems. They let you iterate through numbers, lists, or other collections.

Basic For Loop

The simplest for loop iterates through a range of numbers:

You can also iterate through a list:

Finding Numbers with Specific Properties

Find all numbers from 1 to 50 that are divisible by 7:

Find all perfect squares less than 100:

Find all numbers from 1 to 100 whose digits sum to 10:

Nested For Loops

You can put one for loop inside another. This is useful for checking pairs of numbers:

Find all pairs (a, b) where 1 ≤ a, b ≤ 10 and a² + b² = 50:

Using For Loops for Accumulation

For loops are great for calculating sums and products:

Calculate the sum of all odd numbers from 1 to 100: