Book Image

Python for Finance

By : Yuxing Yan
Book Image

Python for Finance

By: Yuxing Yan

Overview of this book

Table of Contents (20 chapters)
Python for Finance
Credits
About the Author
Acknowledgments
About the Reviewers
www.PacktPub.com
Preface
Index

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:

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 i

In the previous two examples, the default incremental value is 1. If we intend to use an incremental value other than 1, we have to specify it as follows:

>>>for i in xrange(1,10,3):
      print i

The output values will be 1, 4, and 7. Along the same lines, if we want to print 5 to 1, that is, in descending...