Up: Python

Control Flow

slide 001 Hello, and welcome to the third episode of the Software Carpentry lecture on Python. This episode will introduce two forms of control flow: while loops, and if/else conditionals.
slide 002 Arithmetic and assignment statements are all very well, but the real power of programs come from:
slide 003 repetition,
slide 004 which is the ability to do something many times, and
slide 005 selection,
slide 006 which is the ability to do one thing rather than another.
slide 007 The simplest form of repetition is the while loop, which does something as long as some condition is true.
slide 008 For example, here is a small program that prints out the numbers 3, 2, and 1 using a while loop.
slide 009 The loop opens with the keyword while, followed by the loop’s controlling test. Since this test is true—i.e., since num_moons is currently greater than 3…
slide 010 …Python executes the statements in the loop body, which is the indented statements under the loop control.
slide 011 This prints out ’3′ and subtracts 1 from num_moons.
slide 012 Python then re-checks the condition. It’s still true…
slide 013 …so the program prints ’2′ and subtracts 1 from num_moons again.
slide 014 Another check, another print statement: the program prints ’1′, then decrements num_moons again. Since the loop’s controlling condition is now false, the program is done.
slide 015 A while loop may execute any number of times, including zero.
slide 016 Here, for example, num_moons is initially -3…
slide 017 …so the loop condition is false the first time it is tested…
slide 018 …and the loop body doesn’t execute at all.
slide 019 The output is therefore the two lines ‘before’ and ‘after’, with nothing in between.
slide 020 It’s important to keep this “zero pass” condition in mind when designing and testing code.
slide 021 A while loop may also execute forever.
slide 022 Here’s another copy of the program that doesn’t subtract 1 from num_moons inside the loop body.
slide 023 It prints ‘before’…
slide 024 …then 3…
slide 025 …then 3 again…
slide 026 …then another 3…
slide 027 and so on.
slide 028 Since the loop’s control condition was true when the loop started, and nothing happens inside the loop to change it, the loop will run until the user gets bored enough to halt it.
slide 029 This is usually not the desired behavior…
slide 030 …but there are cases we’ll see later where an apparently infinite loop is useful.
slide 031 Why does Python use indentation to show which statements are in the loop body, when other languages use begin...end or curly braces?
slide 032 Because studies have shown that’s what people actually pay attention to.
slide 033 Every textbook on C or Java has examples where indentation and bracing don’t match, which makes it harder to see the errors in programs. Python simply avoids the problem.
slide 034 It doesn’t matter how much indentation you use, but the whole block must be consistent, i.e., if the first statement is indented by four spaces, the rest of the block must be indented by the same amount.
slide 035 The Python style guide (known as PEP 8) recommends 4-space indentation.
slide 036 And please use spaces, rather than tabs, since different editors display tab characters with different widths.
slide 037 while loops allow programs to repeat things; if, elif, and else allow them to make choices.
slide 038 Here’s an example:
slide 039 Since moons is not less than zero…
slide 040 …the program does not execute the first block of code (which would print ‘less’).
slide 041 Similarly, moons isn’t zero…
slide 042 …so the second block isn’t executed, either.
slide 043 Finally, since no other choice was taken…
slide 044 …the statements under the else are executed…
slide 045 …and the program prints ‘greater’.
slide 046 A set of choices like this always starts with if and a condition…
slide 047 It can have zero or more elif clauses, each with its own test…
slide 048 And optionally an else with no test to execute if nothing else is done.
slide 049 Tests are always tried in order; as soon as one test is true, its block of statements is executed, and no other branch is tested.
slide 050 Of course, blocks of code may contain other blocks.
slide 051 For example, in this program an if is nested inside a while.
slide 052 The while counts from 0 to 10.
slide 053 And the if prints out odd numbers.
slide 054 The combination prints out all the odd numbers between 0 and 10.
slide 055 Here’s a better way to do the same thing:
slide 056 start num at 1, and add 2 to it each time through the loop.
slide 057 The loop runs half as many times, but the output is the same.
slide 058 Writing a simple program that works, then tweaking it to make it more efficient, is a common pattern in programming. Another is to write programs top-down, solving one problem at a time.
slide 059 To see how this works, let’s write a program to print out all the prime numbers less than 1000.
slide 060 The skeleton is simple: start with 2 (since 1 isn’t a prime), and loop up to 1000. If the number is prime, print it out.
slide 061 By definition, a number is prime if it cannot be evenly divided by anything except 1 and itself.
slide 062 The simplest way to check is to try dividing it by each number that’s less than it, so we write another loop.
slide 063 Saying that it can be divided evenly is the same as saying that there’s no remainder…
slide 064 …which tells us how to fill in the last bit of our program.
slide 065 Putting the whole thing together gives us this, which is just the bits of code we wrote put in order.
slide 066 Now let’s look at a more efficient version.
slide 067 This code is almost the same as what we just saw…
slide 068 …but it takes advantage of the fact that a number can’t be evenly divided by anything greater than its own square root. It’s a neat idea, and can save a lot of work, but unfortunately this program contains a bug.
slide 069 As a lot of programmers will tell you, any code that hasn’t been tested is almost certainly wrong.
slide 070 Let’s change the bound on the outer loop so that we only print out the primes up to 10.
slide 071 Here’s its output.
slide 072 Whoops: 4 and 9 aren’t prime.
slide 073 Where’s the bug?
slide 074 One clue is that 4 and 9 are both perfect squares.
slide 075 So let’s have a look at the one thing we changed: the condition of the inner loop.
slide 076 Two squared is four…
slide 077 …but since the loop condition is less than, we never actually check to see whether 4 can be divided by 2…
slide 078 …or whether 9 can be divided by 3, and so on. The condition should be “less than or equal”; if we make this change, the program produces the correct output once again.
slide 079 This is a common pattern in programming: write a simple version that’s easy to check, then gradually introduce complications, checking for bugs and fixing them at each step, to produce something that’s faster or more powerful, but still correct.

  1. Gorden Jemwa
    January 26th, 2011 at 20:55 | #1

    A quick question on the on the program for printing primes: Can we not ( for more efficiency) modify the second WHILE condition to also check if the variable is_prime is not yet false, i.e. change the test to

    while ((trial**2 < num) and is_prime)):

    Otherwise, unnecessary execution will be performed although an earlier test has already shown that the number is not a prime.

  2. luis
    January 27th, 2011 at 13:51 | #2

    @Gorden Jemwa

    Yep, you are correct. If you introduce the is_prime check, the loop would end as soon as a divisor is found.

    (Note that you don’t need the external parenthesis: “while (trial**2 < num) and is_prime:” would suffice.)

  3. jarav
    May 20th, 2011 at 11:48 | #3

    The correct way to answer Gorden Jemwa’s concern would be to put a ‘break’ inside the ‘if’ condition that tests for the remainder.

    if num % trial == 0:
    is_prime = False
    break

  1. No trackbacks yet.