O'Reilly logo

Python for Finance by Yuxing Yan

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Understanding a for loop

A for loop is one of the most used loops in many computer languages. The following flow diagram demonstrates how a loop works. Usually, we start with an initial value. Then, we test a condition. If the condition is false, the program stops. Otherwise, we execute a set of commands:

Understanding a for loop

The simplest example is given as follows:

>>>for i in range(1,5):
      print i

Running these two lines will print 1, 2, 3, and 4. We have to be careful with the range() function since the last number, 5, will not be printed in Python. Thus, if we intend to print from 1 to n, we have to use the following code:

>>>n=10
>>>for i in range(1,n+1):
 print ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required