Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
IPython Notebook Essentials

You're reading from   IPython Notebook Essentials Compute scientific data and execute code interactively with NumPy and SciPy

Arrow left icon
Product type Paperback
Published in Nov 2014
Publisher
ISBN-13 9781783988341
Length 190 pages
Edition 1st Edition
Tools
Arrow right icon
Author (1):
Arrow left icon
Luiz Felipe Martins Luiz Felipe Martins
Author Profile Icon Luiz Felipe Martins
Luiz Felipe Martins
Arrow right icon
View More author details
Toc

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. Then, an if-then-else statement is used to decide if the roots are real or imaginary, according to the sign of the discriminant. Note the indentation of the code. Indentation is used in Python to define the boundaries...

lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime
Banner background image