You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
177 lines
16 KiB
177 lines
16 KiB
<!doctype html> |
|
<html> |
|
<head> |
|
<meta charset="utf-8"> |
|
<meta http-equiv="X-UA-Compatible" content="IE=edge"> |
|
<meta name="viewport" content="width=device-width, initial-scale=1"> |
|
<title>My Learning Website</title> |
|
<link href="/styles/styles.css" rel="stylesheet" type="text/css"> |
|
<link href="/programming/styles/styles.css" rel="stylesheet" type="text/css"> |
|
<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries --> |
|
<!-- WARNING: Respond.js doesn't work if you view the page via file:// --> |
|
<!--[if lt IE 9]> |
|
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> |
|
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> |
|
<![endif]--> |
|
</head> |
|
<body> |
|
|
|
<div class="banner"> |
|
<h1 class="courselink">Python Essential Training</h1> |
|
<h2 class="lecturer">LinkedIn Learning : Bill Weinman</h2> |
|
<h2 class="episodetitle">Loops</h2> |
|
</div> |
|
|
|
<article> |
|
<h2 class="sectiontitle">Python Loops</h2> |
|
<p>Python has two basic types of loop, a while loop and a for loop. A while loop iterates based on some condition and ceases operation when the condition becomes false. It doesn't rely on a variable that is updated in each iteration, but its condition must have the capacity to become false, otherwise you may create an infinite loop.</p> |
|
<p>An example of this might be where the user is expected to select a menu option, let's say a number between 1 and 5. The while loop might continue while the option selected by the user is not between 1 and 5.</p> |
|
<pre class="inset"> |
|
while (x < 1 and x > 5).</pre> |
|
<p>The other type of loop is a for loop which is designed to run a fixed number of times. In Python, there are several ways to control the iterations such as iterating through a collection or using a range.</p> |
|
<h2 class="sectiontitle">The while Loop</h2> |
|
<p>Let's look at another example of a while loop and examine it in a little more detail.</p> |
|
<pre class="inset"> |
|
secret = 'swordfish' |
|
pw = '' |
|
|
|
while pw != secret: |
|
pw = input("What's the secret word? ")</pre> |
|
<p>When we run this, the variable secret is set to a string value, 'swordfish'. A second variable called pw is initialised with an empty string. The condition that we are basing this while loop on is that these two variables don't have the same value. Note that if they were the same, the condition would evaluate to False immediately and the code block associated with the while loop will never be executed. This is an important point because it means that the code in a while loop might never be executed. In a very simple example like this one, we have full control over the condition so we can be certain that it will run, but in a real life situation, it may be much more difficult to determine how the condition will be evaluated so it may well be less certain whether the code in a while loop will be executed.</p> |
|
<p>So, in this case, the variables have been initialised in a way that guarantees that the condition will evaluate to true when the while loop executes. When the code in the loop executes, the user is asked to input a string and pw is set to the string that the user inputs and the loop iterates again.</p> |
|
<p>This means that the condition is evaluated again, so again the interpreter checks whether the variable pw and secret are the same. If they are not the same, the condition evaluates to True and the loop moves on to the next iteration. However, if they are the same, the condition evaluates to False and the loop terminates and, in this case, the program terminates.</p> |
|
<p>There are a couple of notable things to mention about this example. Semantically, what is happening is that the user is being asked to enter a string which might be a password for example, and the loop continues executing until the user has typed in the correct string (swordfish in this example).</p> |
|
<p>The other noteworthy thing is that we are using a negative condition. What I mean is that we want the loop to terminate when a specific condition is met (when the pw variable matches the secret variable). That means that the condition that causes the loop to continue executing is the opposite of this. So, rather than testing whether the two variables are the same, we are testing for the condition that they are NOT the same.</p> |
|
<h2 class="sectiontitle">The for Loop</h2> |
|
<p>Let's start by looking at an example of a for loop.</p> |
|
<pre class="inset"> |
|
animals = ( 'bear', 'bunny', 'dog', 'cat', 'velociraptor' ) |
|
|
|
for pet in animals: |
|
print(pet)</pre> |
|
<p>Here, we have a collection on the first line, a tuple containing a list of animals. The loop has a control variable called pet and this works by representing each element of the tuple once in an iteration. For example, in the first iteration, the value of pet is animals[0] so the print statement is equivalent to</p> |
|
<pre class="inset"> |
|
print(animals[0])</pre> |
|
<p>Although I referred to pet as the control variable, it would probably be more accurate to say that the controller in this loop is the length of the tuple (the number of elements it contains) since this is the number of times the loop will run.</p> |
|
<p>If you are familiar with a C-style for loop, it is a common syntax used in a lot of programming languages so you may be familiar with it without knowing it, the type of for loop shown above will look pretty strange. Python doesn't have a C-style for loop but to give some comparison, the syntax for a C-style loop that outputs integers from 1 to 10 is shown below.</p> |
|
<pre class="inset"> |
|
#include <stdio.h> |
|
|
|
int main() |
|
{ |
|
for (int i = 1; i <= 10; i++) { |
|
printf("i is %d\n", i); |
|
} |
|
}</pre> |
|
<p>For anyone interested in trying out this loop to confirm that it works, you can run it on an online compiler at <a href="https://www.onlinegdb.com/online_c_compiler">onlinegdb.com</a>, or any compiler you have set up for C. If you wanted to write a for loop in Python that prints out the numbers from 1 to 10, you would use the range function (see the section on <a href="types.html#range">Types and Values</a> for more information on how the range function works).</p> |
|
<p>The loop would look something like this.</p> |
|
<pre class="inset"> |
|
for i in range(1, 11): |
|
print (i)</pre> |
|
<p>In the C-style loop, there are three important bits of information relating to the control variable, i. The first is the starting value for i (i=1). The second is the value that causes the loop to terminate (i <= 10, the loop continues until this is no longer true which in this case will be when I reaches a value of 11) and the modification to the value of i (i++, it is acting as a counter so you need to increment it in every iteration).</p> |
|
<p>In the Python loop, the range provides all three of these although they don't always need to be explicitly specified. The only parameter that is mandatory is the condition for terminating the loop. That is, the value that the control variable must reach for the loop to stop. In our example, the loop stops when the control variable reaches a value of 11. Since the loop terminates when this value is reached, this value isn't printed and this is important. If we had created the loop like this.</p> |
|
<pre class="inset"> |
|
for i in range (1, 10)</pre> |
|
<p>this would only output the numbers from 1 to 9. Obviously, neither of these are correct or incorrect without knowing what the intention is. If you know that the code is supposed to output the numbers 1 to 10, you can say that the value specified in the range should be 11. The important point to remember is that if you are working with a range, the value specified as the terminating condition will not be processed (the loop will terminate without executing any of the loop code.</p> |
|
<p>The initial value is optional but of it is omitted, the range starts from 0. In this case, we wanted to start this from 1 so this has been specified as part of the range.</p> |
|
<p>In a Python loop, there is no need to specify a change to the control variable because we are using a range which iterates through all of the numbers from 1 to 10, in this example. However, this is essentially assuming that the counter is incremented by 1 for each iteration. However, if you want to print out only the odd numbers in the range, we would want to increment the control variable by 2 each time and this would be specified as a third parameter for range.</p> |
|
<p>To summarise the range parameters, we can supply 1, 2 or 3 parameters. If only one is supplied this is the value used to determine when the loop is complete. If two are supplied, the first is the starting value for the loop control variable and the second is the terminating value.</p> |
|
<p>These are also the first two parameters in the same order if three parameters are supplied and the third is the value by which the variable is incremented for each iteration, sometimes referred to as the step. These can be summarised in relation to our C-style loop like this.</p> |
|
<table> |
|
<tr> |
|
<th>Number of parameters</th> |
|
<th>Identification of parameters</th> |
|
<th>Equivalent in C-style loop</th> |
|
<th>Range</th> |
|
</tr> |
|
<tr> |
|
<td>1</td> |
|
<td>terminating value</td> |
|
<td>i <= 10</td> |
|
<td>for i in range(11)</td> |
|
</tr> |
|
<tr> |
|
<td>2</td> |
|
<td>initial value, terminating value</td> |
|
<td>i = 1; i<= 10</td> |
|
<td>for i in range (1, 11)</td> |
|
</tr> |
|
<tr> |
|
<td>3</td> |
|
<td>initial value, terminating value, increment value</td> |
|
<td>i = 1; i<= 10; i++</td> |
|
<td>for i in range (1, 11, 1)</td> |
|
</tr> |
|
</table> |
|
<p>Just a quick reminder, if you omit the third parameter, this defaults to 1 so the control variable is incremented by 1 in each loop iteration. If you omit the second parameter, the default initial value is 0. This cannot be omitted if you want to specify the third parameter, so if you want the control variable to increment by, say, 2 in each iteration, you must specify the initial value even if it is 0.</p> |
|
<p>It may also be worth mentioning the fact that if you are writing a loop in a language that uses C-style for loops, obviously this applies to C or C++ but also Java, JavaScript and many others, all three parameters must be specified.</p> |
|
<h2 class="sectiontitle">Additional Controls</h2> |
|
<p>Python has three additional controls that can be used to control the flow of execution. They are not specific to any type of loop so they can be used with either while loops or for loop. They are</p> |
|
<div class="inset"> |
|
<p>• continue - terminates the current iteration of a loop and moves on to the next iteration. This happens automatically when the interpreter executes the code in the last-line of the loops code block so if continue is the last line of the code block, it will have no effect since the loop would automatically continue at that point anyway.</p> |
|
<p>• break - terminates the loop completely. In theory, it could be the last line of a code block. For example, you might put it inside an if statement which checks for some condition and terminates the loop, depending on the evaluation of the condition. If you have the break statement on its own (so not dependent on any condition), this certainly does have an effect on the flow of execution for the loop. What that would do is terminate the loop at the end of the first iteration. Using a conditional break at the end of a loop does make sense, but an unconditional break would mean that your loop is not actually a loop since it cannot execute its block more than once, so there is no sensible reason for doing that!</p> |
|
<p>• else - this goes after the loops code block and it is executed if the loop ends normally. If it is terminated by a break statement, the else clause will not be executed.</p> |
|
</div> |
|
<p>This usage of else is, to my knowledge, peculiar to Python so it may be helpful to see an example of it. The following snippet of code demonstrates the use of all three.</p> |
|
<pre class="inset"> |
|
#!/usr/bin/env python3 |
|
# Copyright 2009-2017 BHG http://bw.org/ |
|
|
|
secret = 'swordfish' |
|
pw = '' |
|
auth = False |
|
count = 0 |
|
max_attempt = 5 |
|
|
|
while pw != secret: |
|
count += 1 |
|
if count > max_attempt: break |
|
if count == 3: continue |
|
pw = input(f"{count}: What's the secret word? ") |
|
else: |
|
auth = True |
|
|
|
print("Authorised" if auth else "Calling the FBI")</pre> |
|
<p>If we run this and input an invalid password until the loop terminates, the output we see is as follows.</p> |
|
<pre class="inset"> |
|
1: What's the secret word? gre |
|
2: What's the secret word? fish |
|
4: What's the secret word? sword |
|
5: What's the secret word? fg |
|
Calling the FBI ....</pre> |
|
<p>If we run it and input the correct password, the output would look something like this.</p> |
|
<pre class="inset"> |
|
1: What's the secret word? sword |
|
2: What's the secret word? fish |
|
4: What's the secret word? Swordfish |
|
5: What's the secret word? swordfish |
|
Authorised</pre> |
|
<p>Before we look into each of the controls, it's worth taking a moment to consider what the loop is and how it can terminate, particularly what would be considered a normal termination. Since it is a while loop, it is designed to terminate when the condition returns a false value. The condition is</p> |
|
<pre class="inset"> |
|
pw != secret</pre> |
|
<p>In this example, the continue statement is checking whether pw and secret are not the same so a false value is returned when they are the same and this ends the loop and can be considered a normal termination.</p> |
|
<p>The other way in which the loop can be terminated is if max_attempts is exceeded which will trigger the break and this is not a normal termination because it terminates the while loop when the condition that should terminate the loop is still true.</p> |
|
<p>This means that the else clause is only executed if the condition has returned a false value, meaning that the correct password has been entered. The code in the else clause sets the value of auth to True.</p> |
|
<p>The final print statement is completely independent of the while loop so it is executed after the loop terminates, regardless of how it was terminated. It uses a ternary operator to output either 'Authorised' if auth returns True or 'Calling the FBI ....' if auth returns False. So, execution of the print statement doesn't depend on how the loop was terminated, but the string that it outputs does. If the user types in the correct password, the loop terminates and auth is set to True so the print statement outputs 'Authorised'. If the user types in the password incorrectly too many times, the break statement is executed, auth is not changed (its default value is False) and the print statement outputs 'Calling the FBI ....'. Don't worry, it doesn't really call the FBI!</p> |
|
<p>The continue is executed if count has a value of 3. Since count is incremented before the value is checked, the condition will be true on the third iteration meaning that the loop's code block will stop executing the current iteration and go on to the next iteration. There is no real reason for doing that here other than to demonstrate how continue works and you can see this in the program output shown above. The continue statement is before the statement where the user inputs the password, and the input prompt displays the value of count, therefore the number of the iteration and we can see that the user is only able to enter the password a maximum of four times because this is skipped on the third iteration. In the output, we can see that the iterations are numbered 1, 2, 4 and 5.</p> |
|
</article> |
|
|
|
<div class="btngroup"> |
|
<button class="button" onclick="window.location.href='operators.html';"> |
|
Previous Chapter - Operators |
|
</button> |
|
<button class="button" onclick="window.location.href='functions.html';"> |
|
Next Chapter - Functions |
|
</button> |
|
<button class="button" onclick="window.location.href='pythonessentialtraining.html'"> |
|
Course Contents |
|
</button> |
|
<button class="button" onclick="window.location.href='/programming/programming.html'"> |
|
Programming Page |
|
</button> |
|
<button class="button" onclick="window.location.href='/index.html'"> |
|
Home |
|
</button> |
|
</div> |
|
</body> |
|
</html> |