APC Australia

Learn to Code Python — Part 3: Going loopy

-

Ever get into trouble at school where the teacher made you write out lines as punishment? If I could’ve beamed knowledge back to my 10-year-old self, I’d have written a couple of lines of Python code and had the whole thing done in a minute.

Getting a computer to do anything more than once requires you either write out code for each time you want that task completed, or you use a clever little function called a ‘loop’. This month, we’re diving into loops and looking at how they can simplify repetitive tasks.

LOOP TYPES

Python has two main code-looping structures — the ‘while’ loop and the ‘for’ loop. A while-loop will repeat a set of code statements as long as a control condition is true, whereas a for-loop will repeat a code-block for a predetermi­ned count. Or to put it another way, you use a ‘while’ loop when you don’t know how many times you want the code to loop, and a for-loop when you do.

THE WHILE-LOOP

Imagine you’re writing a simple guessing game, where the code picks a random number between 1 and 100, for example, and the user has to guess it. The question you can’t answer is how many guesses the user will need to guess the correct number.

Without a loop, you’d just have to load up as many ‘input’ and ‘if’ statements into your code as you’d think it would take to guess the number. Yuck! I’ve even written the ‘Badly-Coded NumberGues­sing Game’ ( badguess.py) to show you just how awful it looks — and it only allows 15 guesses before it gives up! But this is exactly where a while-loop is perfect — when you don’t know how many times you need the code to run. The structure of a while-loop in Python is pretty straightfo­rward: while (condition-statement): code-statement(s)

The ‘while’ keyword starts us off and then there’s a ‘condition-statement’ inside the brackets. Remember from last time, a condition-statement is one that can evaluate to true or false. The while-loop first tests the condition-statement and while ever that statement holds true, it runs the loop code. Let’s say we have two variables, each holding a number — variable ‘guess’ holds the number the user guessed and variable ‘correct’ holds the correct number. A condition-statement can be

the two variables are not equal, which could look like this: while (guess != correct): code-statement(s)

Now the code-statements inside the while-loop (remember, they must be tab-indented) will continue to loop, executing in top-down order until the while statement finds the value in ‘guess’ stops not-equaling the value in ‘correct’.

We can now write the whole code as: import random correct = random. randint(1,100)

guess = 0

print (“The better-coded ‘Guess a 1-100 number’ game!!!”) while (guess != correct):

guess = int (input (“Guess the number:”))

if (guess != correct): print(“Nope, wrong - guess again.”) print(“You guess it!!!”)

The ‘import’ statement imports the ‘random’ code library and the second line uses the random library’s ‘randint’ (random integer) function to generate a random number between 1 and 100, storing it in the variable ‘correct’. Next, we initialise the ‘guess’ variable by loading it with zero, print a welcome message and then we hit our while-loop. While the value of the ‘guess’ variable is not equal to the value of the ‘correct’ variable, we run the loop code. We start by asking the user to guess the number. The if-statement checks to see if the user has entered the correct value.

If the value of ‘guess’ is not equal to the value of ‘correct’, we print the ‘guess again’ output.

Since this is the end of both the if-statement and the while-loop code-block, it then goes back to the start of the while-loop to check the condition statement again and if the two variables are still not equal (meaning the latest guess is wrong), runs through the loop again. Hopefully, you can see this loop continues until the user either gets the right answer or puts a chair through the computer, whichever comes first.

FOR-LOOP

The while-loop is ideal for when you don’t know how many loops you’ll need, but when you do know, the for-loop is perfect. For-loops work differentl­y, because you no longer have a condition-statement; instead, you have a variable that steps through a list of integers or strings, or, more practicall­y, a range of integers using the ‘range’ function: for variable in range(start, stop, step): code-statement(s)

where ‘start’ is the initial integer start point, ‘stop’ is one past the last integer you want to count and ‘step’ is the gap between each integer. For example, to create a range of odd numbers between 1 and 10, you’d code: range(1, 11, 2)

Let’s say we wanted to add up the integers to 1,000 and print the result. We can do that easily using the following code: total = 0 for nextInt in range(1,1001):

total += nextInt print(“Sum: “,total)

We set the for-loop to run 1,000 times using the range function. The code within the loop is a short-hand for ‘total = total + nextInt’, or add the current value of variable ‘nextInt’ to the value of variable ‘total’ and store the result in variable ‘total’. When the loop completes, it then prints the value of the ‘total’ variable to the screen. Now if I was ten years old again and asked to write out ‘I will not leave my desk like a rubbish tip’ 100 times, I’d write the following and go out to lunch: for nextLine in range(0, 100): print(“I will not leave my desk like a rubbish tip.”)

NESTED LOOPS

What’s cool about loops is that you can also run loops inside loops. They’re called ‘nested loops’ and they can save you even more lines of code.

Let’s say we wanted to print out multiplica­tion tables from one to 12. Without loops, we need 156 print statements to go from 1x0 to 12x12! With a single for-loop, we cut that down to 15. But with nested loops, we drop that to just four: for num1 in range(1,13): for num2 in range(0,13): print(num1,’x’,num2,’= ’,num1*num2) print()

But how do nested loops work? Let’s call the ‘num1’ loop the ‘outer’ loop and the ‘num2’ loop the ‘inner’ loop. Here’s what happens — the outer loop starts at the beginning of its range, which is ‘1’ and starts to run its loop code. The first line of that loop code is the inner for-loop — it starts at the beginning of its range, which is ‘0’.

The inner loop then begins its loop code, which is the print statement. Num1 as ‘1’ and num2 as ‘0’ gives the

print-statement result ‘1x 0 = 0’. That’s the end of the inner loop code, so we go back to the inner loop’s for-loop code line, which increments num2 to ‘1’. We run the inner loop code again and the result is ‘1x 1 = 1’. This inner loop continues until we get to ‘12’ and the print result ‘1 x 12 = 12’.

At this point, the inner loop has now completed, we jump back out to the outer loop, which finishes by printing a blank line for clarity. That’s the end of the outer-loop code, so we go back to the outer for-loop code line at the top, which increments variable ‘num1’ to 2.

We now run the outer-loop code again and the first line is the start of the inner loop. This begins at the start of its range, being ‘0’ and then runs the inner-loop code, which is the print statement, this time giving ‘2x 0 = 0’. The loop code completes and goes back to the inner loop for-loop code, incrementi­ng num2 to ‘1’. We run the inner loop code and print ‘2x 1 = 2’.

Cutting a long story short, the inner loop must fully complete its run each time before incrementi­ng the outer loop, but as you can see from the output, the result is a complete 12-times table from 1 to 12 in just four lines of code.

KEEPING TIME

In theory, there’s no limit to the number of loops you can have nested, but in practice, you want to keep a lid on it, otherwise things can go pear-shaped. A simple example of four nested loops is building a timer with seconds, minutes, hours and days. Obviously every 60 seconds is a minute, every 60 minutes an hour, every 24 hours a day and every seven days a week — sounds ripe for nested loops. Here’s how it looks: from time import sleep for days in range(0, 7): for hrs in range(0,24): for mins in range(0,60): for secs in range(0,60): print(days,’:’ ,hrs,’:’,mins,’:’,secs) sleep(1)

The code here is similar to the times tables, except that we now have four loops running. The easiest way to think of it is the inner loop always spins the fastest and the outer loop, the slowest.

The two lines of code you won’t have seen before are the ‘import sleep’ and the ‘sleep(1)’ statements. The first imports the ‘sleep’ function from the Python’s time library and the second forces the code to sleep — ‘do nothing’ in other words — for one second. Now in practice, this is a horrible way to code a timer because that one-second sleep delay won’t be exactly one second. There are much better ways to do this, but we’re not quite there yet, so we have to crawl before we can walk. That said, the looping works perfectly and if you watch the output, you’ll see that each time unit meets its specified range. To speed things up when running the code, just delete the last line. Close the Python Shell to get it to stop.

GET IT RIGHT

Finally, we’ll combine a while-loop with a new feature to perform some on-the-fly user input validation. Suppose we’re writing a cash-register program to add up a series of prices — what do we do if the user accidental­ly enters in nonnumeric characters? This is why user input validation is so important — you want to be able to cope with user error without the code crashing.

Open the ‘cashreg.py’ source code and take a look. You’ll see it has a single while-loop, but inside the loop is a new function, the ‘try-except’ clause. You can think of this as a bit like an if-else statement for error-checking. In the ‘try’ clause, you load up the statements you want to try to run — in this case, asking the user for a new price, adding it to the total and printing the total nicely to the screen. In that first line, we’re trying to turn the input into a floating (decimal) number, but if the input contains alpha-characters, it’ll create an error. Normally, the code would then crash, but here’s where the ‘except’ clause comes in — the error generated is a ‘ValueError’ error, which the ‘except’ clause now catches, runs its print code line and warns the user. Since this is also the end of the whileloop code, we go back to the while-loop condition-statement, which is still true (the user hasn’t entered zero), so the while-loop runs again, hits the try clause and asks the user for a new price. If the user gets it right, it adds the new value to the ‘total’ variable, prints the total, skips the except clause and goes back to the while-loop condition-statement again.

If the user enters ‘0’, meaning they’ve had enough, the try clause continues, adds zero to the total, prints it, skips the except clause, goes back to the whileloop conditiona­l-statement, which, this time, is no longer true, quits the loop and we can all go home.

GET INTO IT!

Being able to code will be one of the key skills to have in the next ten years and Python is an ideal way to get the basics under your belt. We’re moving along at a decent clip, so if you’re struggling a bit, the best thing is to sit down and play with the code. You can’t learn to drive a car from just reading the manual and the same goes for coding, so get into it!

 ??  ?? Summing integers together to 1,000 using a single for-loop.
Summing integers together to 1,000 using a single for-loop.
 ??  ?? Two nested loops make printing times tables easy.
Two nested loops make printing times tables easy.
 ??  ?? Nesting multiple loops really shrinks your code.
Nesting multiple loops really shrinks your code.
 ??  ?? Using a while-loop is a better way to code a guessing game.
Using a while-loop is a better way to code a guessing game.
 ??  ?? Even with user error, the cashreg.py code correctly adds up prices.
Even with user error, the cashreg.py code correctly adds up prices.
 ??  ?? While-loops can handle loop indefinite­ly...
While-loops can handle loop indefinite­ly...
 ??  ?? The try-except clause allows for user error without crashing.
The try-except clause allows for user error without crashing.
 ??  ?? How not to code a ‘guess the number’ game.
How not to code a ‘guess the number’ game.
 ??  ?? A simple (somewhatin­accurate) timer with four nested loops.
A simple (somewhatin­accurate) timer with four nested loops.
 ??  ?? Four lines of code can create multiplica­tion tables from 1 to 12.
Four lines of code can create multiplica­tion tables from 1 to 12.

Newspapers in English

Newspapers from Australia