Tuesday, 25 April 2017

Introduction to Python 4 - Repeating yourself

You've learned quite a lot so far in the previous tutorials. In this one we tackle something that might feel a bit complicated but, if you take it one step at a time, is not too daunting.

We are going to deal with loops.

No, nothing to do with tying knots, loops are programming constructs that let you repeat things. A typical game runs in a loop - it repeatedly looks at buttons that are pressed and moves things on the screen until, either the game is won (or lost) or the player decides to quit.

Let's write a little guessing game. We are going to get a random number between 1 and 10 and the player tries to guess the right number in the shortest number of guesses.

First we need to get a random number for which we use the random package. Unlike datetime, in the last program, we are not using a sub-package, so the command to include random is simply:

import random

From this package we are going to use the function randint. This takes two parameters as inputs and returns a result that is a pseudo-random integer number between those two numbers. So the line


will gives us a result that is from 1 to 10, inclusive. We are going to assign that value to the variable num, like this

num = random.randint(1,10)

Now num has an integer value (remember, an integer is a whole number). But when we come to get an input from the player, this will be a string. That means that when the player enters the value "1", it is not a numerical value but the character "1", i.e. a short piece of text. Not the same thing as an integer.

Remember the comparison operators <, >, ==, etc.? They give you an answer of True or False, so if I write:

1 == 1

that is a True statement. If I write

"aardvark" == 1

that is obviously False. But similarly, if I write

"1" == 1

that is also False. However the two statements

1 == 1


"1" == "1"

are both True.

We cannot sensibly compare the value of a string with the value of a number, even if they look similar.

So to make life easier, we are going to convert the randomly generated integer value to a string. We do this by using a buit-in function called str(). We use it like this:

answer = str(num)

So now the variable answer has, what we call, the string representation of num. If num had the integer value 5 then answer will have the string value "5".

Here's the whole program

# Simple guessing game
# the program will think of a number between 1 and 10
# you have to guess the right answer

import random

num = random.randint(1,10) # get a number between 1 and 10
answer = str(num)          # convert it to a string
guessed = False            # initialise to False

while guessed == False:
 guess = input("Guess a number: ")
 if guess == answer:
  guessed = True

print("The answer was "+answer)

Just a second, what are those strange lines at the beginning that start with #?

Those, my dear programmer, are comments.

Comments are used to add descriptions or explanations to a program. They begin with a # and end at the end of the line. You can see two ways of using them here. The first comments take up the whole line and explain what is going on below and, later, you can see comments after a statement which explain what the statement is doing. Comments are for the person reading the program and can be very convenient for understanding the program's operation. They are ignored by Python.

Now copy this into a new file in Geany an save it as (or something similar). Make sure you copy the layout exactly as shown - the indentation is very important. 

Now run it and see how long it takes you to guess the right number.


Before we go any further, I need to make a confession. Remember that, previously, I said there were two basic data types, numbers and text? Well, I lied. There is another one that we have already come across, but may be didn't notice, when we were making decisions.

This third basic type can have one of two values, True or False. These are called boolean values. When we make comparisons, as we were doing just now, the result is a value of True or False, and we can use these values directly in a program. We can assign a value of True or False to a variable, or we can compare the value of a variable to True or False. We see this in our program with the line

guessed = False
Here we are introducing a variable and assigning it the boolean value False. And what this represents is the state of the game. While the value of guessed continues to be False we want the player to carry on guessing. When the player guesses the right answer, we set the value of guessed to True and that signals that the game has ended. So, at the beginning of the game we set the value to False.

Notice that, in Python, the words True and False both begin with a capital letter.

The while loop

No we come to the subject of this lesson, a loop. What we have here is a while loop and what it does is repeat one or more lines of code while a particular boolean condition is True.

It begins with the line

while guessed == False:
which simply means that while the value of the variable guessed has the value False, repeat the indented lines of code that follow. And keep repeating them until the value of guessed changes. Note the colon at the end of the line - it has to be there.

The lines that are indented and so will be repeated are

    guess = input("Guess a number: ") 
    if guess == answer: 
       guessed = True

We should be familiar with all of this. The first line prompts the user to input a guess at the number. Next we have an if statement (like in the last lesson). This tests to see if the value of guess is the same as the value of answer. If it is the same then the following (two) indented lines are executed. These first print a congratualtory message and then sets the value of guessed to True, indicating that we have a correct answer.

This is all happening inside the loop, so the next thig is that we go back to the lie that begins while. This check the value of guessed and if it is still False we repeat the loop code again (i.e. we get another guess). If guessed is no longer False (meaning we have a correct answer), the code inside of the loop (the indented code) is not executed and we jump down to the next line, which is

print("The answer was "+answer)
This simply prints the message constructed by concatenating the string "The answer was " with the value of the variable answer.

Phew! That's it. Your first loop.

We've covered quite a lot here so we are going to call it a day, for now. But here, again is a slightly more formal description of the while loop.

While a bit more formally.

The while loop consists of the word while followed by a boolean expression, i.e. something that results in the value True or False. We can use any of the comparison operators that we saw in the previous tutorial, such as <, >, !=, etc.

The first line ends with a colon and the lines that should be repeated are indented. The first line that is not indented is where the program continues after the loop has finished.

There's more to cover about loops but we'll do that another day.

A challenge

While you are waiting to do that, here's a challenge. Modify the guessing game program to print out a message after each guess that says something like "Too high!" or "Too low!".

Hint: you will need to use two more if statements. 

No comments:

Post a Comment