Book Image

Scientific Computing with Python 3

By : Claus Führer, Jan Erik Solem, Olivier Verdier
Book Image

Scientific Computing with Python 3

By: Claus Führer, Jan Erik Solem, Olivier Verdier

Overview of this book

Python can be used for more than just general-purpose programming. It is a free, open source language and environment that has tremendous potential for use within the domain of scientific computing. This book presents Python in tight connection with mathematical applications and demonstrates how to use various concepts in Python for computing purposes, including examples with the latest version of Python 3. Python is an effective tool to use when coupling scientific computing and mathematics and this book will teach you how to use it for linear algebra, arrays, plotting, iterating, functions, polynomials, and much more.
Table of Contents (23 chapters)
Scientific Computing with Python 3
Credits
About the Authors
About the Reviewer
www.PacktPub.com
Acknowledgement
Preface
References

Repeating statements with loops


Loops are used to repetitively execute a sequence of statements while changing a variable from iteration to iteration. This variable is called the index variable. It is successively assigned to the elements of a list, (refer to Chapter 9, Iterating) :

L = [1, 2, 10]
for s in L:
    print(s * 2) # output: 2 4 20

The part to be repeated in the for loop has to be properly indented:

for elt in my_list:
    do_something
    something_else
print("loop finished") # outside the for block

Repeating a task

One typical use of a for loop is to repeat a certain task a fixed number of times:

n = 30
for iteration in range(n):
    do_something # this gets executed n times

Break and else

The for statement has two important keywords: break and else. break quits the for loop even if the list we are iterating is not exhausted:

for x in x_values:
   if x > threshold:
     break
   print(x)

The finalizing else checks whether the for loop was broken with the break keyword. If it was not broken, the block following the else keyword is executed:

for x in x_values:
    if x > threshold:
       break
else:
    print("all the x are below the threshold")