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...