Introduction to Programming Week 4


Part 1: Selection

It's useful to be able to write programs that behave differently when given different input. In Python we can do this with if-statements, which will execute the block of code following them only if a specified condition is met. If the condition isn't met the code will be skipped over, and not executed.

The condition in an if-statement must be an expression that evaluates to a boolean (that is, either true or false). For this we can use relational operators, and we can create more complex expressions using boolean operations.

The general notation for an if-statement is, perhaps rather predictably, the reserved word if, followed by the condition (an expression that evaluates to true or false), followed by a colon. The block of code we want executed if the condition is true must then be indented on subsequent lines. For example, the following code will print something if the variable x is less than 5:

if x<5:
    print("x is less than five.")

We can also add more cases to our if-statement with the keyword elif (short for else if).

if x<5:
    print("x is less than 5.")
elif x<10:
    print("x is less than 10, but greater than or equal to 5.")

When we string together cases with elif this way at most one of the cases will ever be executed, and Python will check them from top to bottom. Hence, in the above example if execution ever reached the elif line we know the if line must not have evaluated to true, so we can assume that x>=5.

Finally, we can have a default case, which is executed if none of the other cases are. These are denoted with the reserved word else, and because they don't test anything there is no conditional (but we still need the colon). To extend our previous example, we might write

if x<5:
    print("x is less than 5.")
elif x<10:
    print("x is less than 10, but greater than or equal to 5.")
    print("x is greater than or equal to 10.")

Part 2: Iteration

Another useful control structure in Python is the loop, which allows the program to repeat a sequence of instructions over and over again. Python actually has multiple types of loops: the for loop gives us an easy way to iterate a fixed number of times, and the while loop will continue executing while a condition is still true.

The notation used in for loops introduces a number of new things. As you might expect, the first line of a for loop starts with the word for and ends with a colon. We have some flexibility with what we put in between, but commonly we'll use the range function and another keyword: in.

By way of example, the following for loop will print out the integers from 1 to 20:

for i in range(1,21):

In this example, several things are happening. First, range returns what is effectively a list of the integers from 1 to 20 (the endpoint isn't included, so we had to go up to 21 to include 20). Then, the for i in part tells Python to loop through the values in the list range created, assigning i to each element in turn. Hence, in the first iteration of the loop the variable i will be equal to the first element of the list, which is just 1, then in the second iteration i will equal 2, and so on up to 20. Hence, when we print i inside the loop we'll print the integers from 1 to 20.

We can replace range(1,21) with any other sequence, and the for loop will iterate through the elements of the sequence.

In contrast, a while loop is more like an extension of the if-statement. The syntax is the same as for an if-statement except, of course, that we use the reserved word while instead of if. Unlike an if-statement, which executes at most once, a while loop will continue to execute until its condition is false. Hence, if the condition is false the first time it's encountered the loop body will never be executed, but if it's always true the loop will go on forever. Usually we want neither of these, so the condition will start out true, then eventually become false after a (possibly unknown until runtime) number of iterations.

While loops can also have else clauses, but they're generally less useful than in if-statements, because they'll always be executed eventually (provided the while-loop eventually terminates).

See Also

Invalid username
Login to AoPS