O'Reilly logo

IPython Notebook Essentials by L. Felipe Martins

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

Control structures

Control structures allow changes to the flow of the execution of code. There are two types of structures that are of interest to us: branching and looping.

Branching allows the execution of different code depending on the result of a test. The following example shows an improved version of code to solve quadratic equations. An if-then-else structure is used to handle the cases of real and imaginary solutions, as follows:

a, b, c = 2., -4., 5.
discr = b ** 2 - 4 * a * c
if discr >= 0:
    sqroot = discr ** 0.5
    x1 = 0.5 * (-b + sqroot)
    x2 = 0.5 * (-b - sqroot)
else:
    sqroot = (-discr) ** 0.5
    x1 = 0.5 * (-b + sqroot * 1j)
    x2 = 0.5 * (-b - sqroot * 1j)
print x1, x2

The preceding code starts by computing the discriminant of the quadratic. ...

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