02-Selection and Repetition
ipynb35 kBPython · 80 cellsSlides of chapter 0
02 - Selection and Repetition
Jupyter notebooks
This is a space where text and code come together to form a coherent document. Throughout the course, we will make use of Jupyter notebooks for illustration purposes and for experimentation.
Motivation
After the introductory set of slides, you should be able to write straigh-line programs. However, in many cases our code's output will depend on a particular truth value (boolean).
For example,
-
What if we need to print the absolute value of a number? We must check its sign first, then output the value accordingly.
-
What if we need to print the multiples of 4 which are less than some input? We must use a loop to do so.
This is where we will use control structures, which are: Selection and Repetition. Selection structures help us in branching-out of straight-lines, while Repetition structures execute a block of code a certain number of times.
Selection
Selection enables the program to branch depending on conditions (boolean values). Example: let's compute the absolute value of an input n.
if statement:
n = float(input("Enter a number: "))
answer = n #initializes the answer to n
if n < 0:
answer = -n
print("The absolute value of", n,"is:", answer)Enter a number: -7.5 The absolute value of -7.5 is: 7.5
if-else statement:
The above allows for execution of an indented block in a single case: when n is negative. Conversely, if n >= 0, we can specify in Python what to do by using the if-else control structure. Going back to the absolute value exercise:
n = float(input("Enter a number: "))
if n < 0:
answer = -n
else:
answer = n
print("The absolute value of", n,"is:", answer)Enter a number: -7.5 The absolute value of -7.5 is: 7.5
multi-way selection (if-elif-else)
In the absolute value exercise, we only have two cases:
-
n < 0, or -
n >=0.
In many scenarios, we have more than 2 cases to check for. In such contexts, we make use of multi-way selection via the if-elif-elif-...-else control structure.
For example, let's take from the user two numbers as inputs and call them x and y.
x = int(input("Enter x: "))
y = int(input("Enter y: "))Enter x: 4 Enter y: 9
Now, let's compare them. There are three cases:
-
x == y -
x > y -
x < y
if x == y:
print("x and y are equal")
elif x > y:
print("x is greater than y")
else:
print("x is less than y")x is less than y
Nested Structure
Nested control structures allow execution of more 'complicated' boolean checks. Example: determining if a number is divisible by 2, by 3, by both, or by neither.
Step 1 is to check if it's divisible by 2 only.
n = int(input("Please enter a number: "))
if n % 2 == 0:
print(n, "is divisible by 2.")
else:
print(n, "is not divisible by 2.")Please enter a number: 6 6 is divisible by 2.
We can nest additional statements inside the above if-else structure to allow for more involved checks. In our example, we need to check if the number n is also divisible by 3.
Step 2 is adding the strucuture for divisibilty by 3.
n = int(input("Please enter a number: "))
if n % 2 == 0:
if n % 3 == 0:
print(n, "is divisible by both 2 and 3")
else:
print(n, "is divisible by 2 only")
else:
if n%3 == 0:
print(n, "is divisible by 3 only")
else:
print(n, "is not divisible by either 2 or 3")Please enter a number: 6 6 is divisible by both 2 and 3
Repetition
The while loop
Selection structures help us branch out into multiple possibilites, but often times, we require that a certain block of code be executed multiple times (until a certain condition becomes false). This is where the while control structure comes in.
For instance, let's print all numbers less than a user input.
n = int(input("Please enter a number: "))
counter = 1 #initialize a counter to 1
while counter <= n:
print(counter)
counter = counter + 1Please enter a number: 5 1 2 3 4 5
The above code enables the program to loop as long as a condition is satisfied. Indeed, as long as what comes after the while statement holds true, the indented block beneath it will keep executing.
Note that incrementing the counter is vital, as it ensures that we don't step into an 'infinite loop'. The following is an example of a faulty while-loop that will go on until the laptop's battery dies down to 0%. To stop the execution, hit the black square in the toolbar.
n = int(input("Please enter a number: "))
counter = 1 #initialize a counter to 1
while counter <= n:
print(counter)Please enter a number: 0
Let's combine Selection with Repetition, to print all multiples of 4 less than n. We can check if the user input n is positive and proceed accordingly. For instance, if the user enters -4 we print an error message.
n = int(input("Enter a positive number n: "))
if n < 0:
print("error: input is negative")
else:
print("The multiples of 4 less than", n, "are:")
i = 0
while i < n:
print(i)
i = i + 4Enter a positive number n: 20 The multiples of 4 less than 20 are: 0 4 8 12 16
Example: computing the sum and average of n integers.
In this example, we will make use of the while structure to input n integers. Inside the loop, we will accumulate the sum of the inputs in a variable called summation.
n = int(input("enter the number of floats: "))
summation = 0 #initalize the summation to 0
i = 1 #initialize the counter of the loop
while i <= n:
message = "Enter number " + str(i) + ": "
x = float(input(message))
summation = summation + x
i = i + 1enter the number of floats: 3 Enter number 1: 2 Enter number 2: 4.5 Enter number 3: 6
Now, we may print the final sum:
print("The final sum is equal to", summation)The final sum is equal to 12.5
Also, since we know the total number (which is n), we can print the average value of the inputs:
avg = summation/n
print("The average value is equal to", avg)The average value is equal to 4.166666666666667
Sentinel-controlled loop
In the above example, we know beforehand (apriori) how many integers we will input. What if the user wants to enter as many numbers as they need? We can achieve this by using a sentinel-controlled loop. The sentinel is a 'special' character that indicates to the program that this is the end of the sequence.
Here is an illustration:
sentinel = input("Enter a sentinel of your choice (*,|,?,^,$): ")
summation = 0
s = input("Enter a number: ")
while s != sentinel:
x = int(s)
summation = summation + x
s = input("Enter another number: ")
print("The final sum is", summation)Enter a sentinel of your choice (*,|,?,^,$): $ Enter a number: 3 Enter another number: 5 Enter another number: 7 Enter another number: $ The final sum is 15
The above code keeps executing until the user enters a sentinel, which makes the s != sentinel condition in the while structure False.
If we need to keep track of how many integers were inserted, we may use a counter to do so. This will be necessary to compute the average in this case, since we don't know beforehand what is n. Indeed, n will be determined dynamically:
sentinel = input("Enter a sentinel of your choice (*,|,?,^,$): ")
summation = 0
n = 0
s = input("Enter a number: ")
while s != sentinel:
x = int(s)
summation = summation + x
n = n + 1
s = input("Enter another number: ")
print("The final sum is", summation)Enter a sentinel of your choice (*,|,?,^,$): $ Enter a number: 3 Enter another number: 5 Enter another number: 7 Enter another number: $ The final sum is 15
Now, we can compute the average since n has been determined in the above:
avg = summation/n
print("The average is:", avg)The average is: 5.0
We may also cover the case where n is equal to 0, so that we avoid division by 0 when computing the average. The following is the complete code:
sentinel = input("Enter a sentinel of your choice (*,|,?,^,$): ")
summation = 0
n = 0
s = input("Enter a number: ")
while s != sentinel:
x = int(s)
summation = summation + x
n = n + 1
s = input("Enter another number: ")
print("The final sum is", summation)
if n != 0:
print("The average is", summation/n)
else:
print("Empty sequence")Enter a sentinel of your choice (*,|,?,^,$): $ Enter a number: 3 Enter another number: 5 Enter another number: 7 Enter another number: $ The final sum is 15 The average is 5.0
for loop
The motivation behind the use of a for loop is to simplify the syntax for counter-controlled while loops. Consider the below while loop, which iterates from start to stop - 1 and displays the counter i.
start = 0
stop = 12
i = start
while i < stop:
print(i, end=" ")
i = i + 10 1 2 3 4 5 6 7 8 9 10 11
We can implement a shorter version of this code using a for loop.
for i in range(start, stop,1):
print(i, end=" ")0 1 2 3 4 5 6 7 8 9 10 11
Note that the default value for start is 0 and for step it's 1. So, we may skip them in the above and write:
for i in range(stop):
print(i, end=" ")0 1 2 3 4 5 6 7 8 9 10 11
In the above structure, the range(start, stop, step) is an iterable.
Meaning, the value of i will iterate over the range [start,end[, with a step. The range can be thought of a list containing the numbers:
[start + step, start + 2*step, start + 3*step, ..., start + c*step], where c is some integer.
For instance, if start = 2, stop = 10, and step = 1, i will assume the values in the list [2, 3, 4, ..., 9]. Note how the range is exclusive in terms of stop, so the last value that i will take in this case is 9 not 10. The variable i will not reach stop.
We've seen how to print multiples of any number less than n, using while-loops. Let's do the same using a for-loop instead.
f = int(input("Enter the factor:"))
n = int(input("Enter n: "))
print("\nThe multiples of", f, "less than", n, "are:")
for i in range(0, n, f):
print(i, end=" ")Enter the factor:3 Enter n: 20 The multiples of 3 less than 20 are: 0 3 6 9 12 15 18
Finally, step can be negative so we can print stuff in reverse order.
for i in range(stop - 1, start - 1, -1):
print(i, end=" ")11 10 9 8 7 6 5 4 3 2 1 0
Note here how we started the range at stop - 1 and ended it at start - 1, so that we get the same output as in the above examples.
Nested loops
As in the case when we nested if structures, we can do the same for loops. Namely, we can have one loop nested in another to achieve a certain objective.
For example, let us take an input from the user and call it n. Our objective is to print the following half-tree pattern:
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
.
.
.
1 2 3 4 5 ... n-2 n-1 n
n = int(input("Enter n (n>0): "))
for i in range(1, n+1):
for j in range(1, i+1):
print(j, end=" ")
print("\n", end="")Enter n (n>0): 5 1 1 2 1 2 3 1 2 3 4 1 2 3 4 5
We can also print the half-tree pattern upside down:
n = float(input("Enter n (n>0): "))
for i in range(n, 0,-1):
for j in range(1, i+1):
print(j, end=" ")
print("\n", end="")Enter n (n>0): 5
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In[23], line 3
1 n = float(input("Enter n (n>0): "))
2
----> 3 for i in range(n, 0,-1):
4 for j in range(1, i+1):
5 print(j, end=" ")
6 print("\n", end="")
TypeError: 'float' object cannot be interpreted as an integerNested loops are extremely common and very useful in programming. You will encounter them very often in this course.
Example: Testing Primality
A number is said to be prime if its divisors are only two numbers: 1 and itself. For example, 2, 3, 5, 7, 11, 13, 17, 19 are all primes. How can we check, for any given integer n, if it's prime or not?
We have to loop over all numbers less than n, i.e., 2,3,4,5,... up to n-1, and check if there exists a number that divides it. If that is the case, the number is not prime.
This is an example of the "True-until-proven-False" pattern, where we start off by assuming that the number is indeed prime and look for evidence to the contrary. To start, let's take the user input and initialize a boolean to True.
n = int(input("Enter an integer: "))
is_prime = TrueEnter an integer: 17
Next, we start our loop from 2 and up to n-1 and check if any one of these numbers in the range divide n.
d = 2
while (d < n && is_prime == True):
if n % d == 0:
is_prime = False
d = d+1
if is_prime:
print(n, "is prime.")
else:
print(n, "is not a prime number.") Cell In[25], line 2
while (d < n && is_prime == True):
^
SyntaxError: invalid syntax
In the primality check, we only need a single evidence to get the answer.
Since all we need to check is that at least one number divides n, we don't really care about the rest of the divisors (if any). Hence, a faster primality check would be to use the break structure to exit out of the loop early. This is especially useful for very large numbers and thus, we can avoid going through the whole list from 2 to n-1.
All we must do is insert a break after line 4 in the above code.
d = 2
while d < n:
if n % d == 0:
is_prime = False
break
d = d+1
if is_prime:
print(n, "is prime.")
else:
print(n, "is not a prime number.")17 is prime.
Float type and accuracy
Recall that the float type is represented with limited precision (8 bytes). Thus, we may encounter approximation errors. For example, the code below should (ideally) print 1 but it does not!
x = 0
for i in range(10):
#print("i is now:",i)
#print("x is (before addition):",x)
x = x + 0.1
#print("x is now (after addition):",x)
#print("----------------------------")
print("x is:", x)
print("Is x equal to", 1, "?")
if x == 1:
print("Yes!")
else:
print("No.")x is: 0.9999999999999999 Is x equal to 1 ? No.
Although the comparison x == 1 gives False, x is arbitrarily close to 1. Hence for floats, the appropriate way to compare two numbers is to use a en error tolerance called 'epsilon', and check if the absolute value of the difference between two floats is less than 'epsilon'. If it is, then the numbers are equal.
Let's do this step.
eps = 10E-6 ##eps = 10**(-6) is an equivalent initialization
print("Is x equal to", 1, "?")
if abs(x-1) <= eps:
print("Yes!")
else:
print("No.")Is x equal to 1 ? Yes!
The Bisection Method
Motivating example: finding the square root of an integer
Let's find an approximation for the square-root of an integer x, where we assume that x>1.
To do so, we can divide the interval from [1,x] into very small equally-spaced points (say, 1000000) and find a number p inside this interval such that p*p is equal to x.
Again, remember that we have to do a float comparison here, so the == operator is not appropriate in this context. Instead, we search for p such that |p*p - x| < epsilon.
x = float(input("enter x (x>1): "))
eps = 1E-6
p = 1
while(abs(p*p - x)> eps):
p = p + 0.000001
print("the square root of", x,"is approximately:", p)enter x (x>1): 4 the square root of 4.0 is approximately: 1.9999999999177334
%%time
x = float(input("enter x (x>1): "))
eps = 10E-6
p = 1
while(abs(p*p - x) > eps):
p = p + 0.000001
print("the square root of", x,"is approximately:", p)enter x (x>1): 4 the square root of 4.0 is approximately: 1.9999979999177335 CPU times: user 70.2 ms, sys: 566 μs, total: 70.8 ms Wall time: 70.7 ms
In the above, we added the %%time command to see how much CPU-time the code uses. Since we have to check for each point in the interval [1,x], this algorithm is relatively slow. Hence the motivation for the bisection method.
The method
Now, let's apply the bisection algorithm and compare the times.
The bisection method splits the region of interest [1, x]=[low, high] in half by assigning a variable mid = (low + high)/2. Next, it compares mid*mid to x:
1) if mid*mid < x: then the value of mid is too small. Accordingly, we set low = mid and the new interval becomes [mid, high]
2) if mid*mid > x: then the value of mid is too large. Accordingly, we set high = mid and the new interval becomes [low, mid]
3) if mid*mid == x: we break out of the loop that keeps updating low and high.
The below is an implementation of the bisection method for approximating a square-root of x <1.
%%time
x = float(input("enter x (x>1): "))
eps = 1E-12
low = 1
high = x
mid = (low + high)/2
while(abs(mid*mid - x) > eps):
if mid*mid < x:
low = mid
else:
high = mid
mid = (low + high)/2
print("the square root of", x,"is approximately:", mid)enter x (x>1): 4 the square root of 4.0 is approximately: 1.9999999999997726 CPU times: user 47 μs, sys: 5 μs, total: 52 μs Wall time: 50.1 μs
In the bisection method, the search interval [low,high] keeps shrinking by half; low and high will get progressively closer to each other until we find a middle point such that |mid*mid - x|<eps.
As you can observe, the difference in CPU times are orders of magnitude apart!
For x = 256, the regular search method takes around 3000 milliseconds of total CPU time, while the Bisection Method takes around 20 milliseconds.
Finally, it is worthy to note that the sqrt() function can be imported from the math module.
from math import sqrt
x = int(input("Enter an integer (x>0): "))
y = sqrt(x)
print("The square-root of", x,"is", y)
print("Using the exponention operator,", x**0.5)Enter an integer (x>0): 16 The square-root of 16 is 4.0 Using the exponention operator, 4.0