27.2. Using an else with a for loop
Python has a cool feature where you can add an else clause to a for loop!
That might sound weird, but you'll see what it does if you the example code.
The else branch runs only if the loop is NOT broken, in this example, if the
thing we're looking for is not found.
This gives us a way to make our Knights of Ni online training password
program much more logical.
1. Complete the for statement on line 4 so that the loop will run 3
times.
2. If the user guesses the password correctly, print "Correct,
authorisation complete."
3. After this line add a break statement to exit the loop since they
were right (still inside the if branch).
4. The first else branch goes with the if and runs if the guess is
incorrect, so print "Incorrect" in here.
5. The second else on line 12 runs if the loop exits normally without
being broken, in this case if the user fails 3 times. Print ""Sorry, 3
incorrect guesses, your account has been locked." in this branch.
6. Click and test your code!
27.3. Use break with a while loop
Because a while loop checks a condition, we can usually just change a
variable inside the loop to switch it off.
Sometimes we might want to do something small, however, that we don't
want to make a whole new variable for. In this case we might use break with
an infinite loop.
An infinite loop can be done in many ways (often accidentally!) but a
deliberate one might look like this: whileTrue:
#dosomething
We can't ever switch it off because the only part to our condition is the word
True, which is always True!
Let's look at forcing a user to enter valid input (validation).
1. Complete the while statement so it is an infinite loop (line 2).
2. If they type in "true" or "false", break the loop (line 6).
3. Otherwise print "Please answer with true or false" (line 8).
4. Click and test your code several times to check all of the branches.
Note that this code is just a snippet; it doesn't actually check if they are right
or wrong, just that they have entered a valid answer. This is important for
writing really good code!
27.4. Use try/except to force numerical input
At the moment, when we use: int(input("Enteranumber:")) our
program crashes if we type in letters, or leave it blank - you can test this by
running the example code.
To get around this, we use try and except. It looks like this: whileTrue:
try:
number=int(input("Enteranumber:"))
break
exceptValueError:
print("Pleaseenteranumber!")
Click here for an explanation.
1. Create an infinite loop using the while statement on line 2.
2. This time we're expecting a height such as 1.8, so add float() to
the input on line 4.
3. If the user enters invalid data (in the except branch), print "Please
enter a valid height in metres e.g. 1.65".
4. Click and test the program with a word, an integer and a float.
Note: If you think the input might be an integer or a float, then use float().
If you don't want to accept decimals, then use int().
27.5. Review quiz time!
Let's review break and continue.
Review Quiz Questions:
1. What does the break statement do?
2. What does the continue statement do?
3. What does the following code print out?
4. What are the keywords that can be used to write code that will
force a user to enter a number?
28. Testing for infinite loops
28.1. Testing expected values
In this lesson you will learn about testing your code. It's really important to
know how to test your code thoroughly if you want to write good code that
works.
There are generally 3 types of input values that we test. For example, if
we're asking the user for the number of hours they exercised for today:
Expected values - the values you expect your user to enter. In this case
0-24 inclusive (24 hours in a day).
Boundary values - data that is on either side of the acceptable limits. In
this case -1 and 0 and 24 and 25.
Invalid or exceptional values - values your program should NOT
accept. In this case for example: three, -3, lots.
1. Click twice, and test this code with an expected value.
2. Click again and try typing in 25.
3. Click once more and try typing in three.
This code works fine for expected values, but it crashes on invalid values
containing letters, and should make us try again if we type in an outer
boundary like 25 or an invalid number like -3.
Extra Note.
28.2. Test boundary values
Here is a new version of our code that has been set up to handle the
boundary input cases properly.
This code snippet now only accepts numbers between 0 and 24. Let's test it
out!
1. Click and type in the first boundary value -1, then the value 0.
2. Click and type in the first boundary value 25, then the value 24.
3. Click one more time and enter an invalid value that contains
letters.
Usually you would pick a sample of expected and invalid values to test your
program on, but it's best to test ALL boundary values because it's the only
way to be sure that you've got all your conditions right.
28.3. Test invalid or exceptional values
Now we just need to make it so that our program doesn't crash when an
invalid value that contains text is entered!
Remember try/except? We're going to use that here.
This version of our code uses the whileTrue: loop to force valid input. If
the user enters a number, we will try to convert it using float(), and if
that works then we will check if their number is in the right range. If not, we
ask them to enter a number in the right range and stay in the loop.
Otherwise (else), if they have entered a number in the right range, we will
break.
The except block runs if the number can't be converted using float(), and
gives them a specific error message. This code handles all expected,
boundary and invalid values.
1. Replace the ??? to complete the if statement on line 5 with a
condition that will make sure the user's input is within the
boundary values.
2. Replace the ??? on line 9 with the correct keyword.
3. Click and test the program with a boundary value that is outside
the boundary then with an expected value.
4. Click and test the program with an invalid value that contains
letters then with an expected value.
Don't worry if the code is a little bit confusing, this is getting quite complex!
If you are keeping up, well done.
28.4. Other ways of testing input data
Python has some other built-in functions that we can use to find out
information about strings: .isnumeric()#Trueifastringcontains
onlynumbers
.isalpha()#Trueifastringhasonlyletters
.isalnum()#Trueifastringhasonlylettersand/ornumbers
(alphanumeric)
An example of where this might be useful is if you wanted to force a user to
enter text only e.g. a name, or numbers and letters only e.g. a serial
number.
1. The code in the editor forces the user to enter a name with no
numbers in it. Click and test it with "9000" to see what happens.
2. Click again and test it with "R2D2".
3. Click once more and enter a valid name.