Monthly Archives: February 2015

Go Loopy (Part I)

While loop

Repeats the execution of a block of code if its condition is true,  the while loop is sometimes referred to as a repeating if statement because the block of code will only execute if a condition evaluates as True. Using IDLE create and run a file with the following (or download this file and run)

# Initialise what is needed by the game
done = False
score = 0
high_score = 121
# game loop, where a game is played
while not done:
    answer = input('Quit Game(y/n):')
    if 'y' == answer.lower():
        done = True
    # Game Logic, simulate by adding points to the game score
    # can input negative and positive integers
    points = int(input('Enter points won this iteration:'))
    score += points
# Display the score plus if you have the high score
if score > high_score:
    high_score = score
    print('New High Score ', high_score)
elif score == high_score:
    print('Your score equals the high_score of ', high_score)
else:
    print('Your score is ', score)

print('Good Bye')

An example of a run on the console looks like:

while_score

The while statement is on line 6 with where the block of code associated with the while state on lines 7 to 13. The while’s condition uses a ‘not’ operation. This boolean operation inverts the boolean value, i.e. inverts True to False and inverts False to True.

When the program executes line 6,  it evaluates the condition to check if we are not done. If this condition is True, i.e. when done is False, then the while’s block of code is executed.

The block of code repeats until the user inputs a ‘y’ or ‘Y’ for the input on line 7,  which causes the variable ‘done’ to be assigned to True and the while’s condition will evaluate to False after completing the while’s block of code.

When the condition evaluates to False the while’s block of code is skipped and code execution skips to line 15 and the score is displayed.

Tuple Type

Like strings tuples are a sequences of used to refer to a set of values. The main difference between tuples and strings is that instead of values been single characters for a tuple the values can be any type,  integers (int),  floats,  strings and even a tuple. As with strings the individual values can be refers using a index to there position in the sequence starting at zero.

Also the values in a tuple once created cannot be changed. Which makes tuples a good type for values that do not change, i.e. constants in a program.

In a python console type the following:

my_info = ('skelly', 'kiernan', 95)
type(my_info)
my_info[0]
my_info[2]
type(my_info[0])
type(my_info[2])
my_info[0] = 'no change'

In the console this will look like:

tuple

Defining Colours

In PyGame tuples are commonly  used to define colours in the form of RGB values.  RGB is a additive colour model based on adding light from Red, Green and Blue light to create the desired colour. The following website gives a short explanation and a color picker that displays the Red, Green and Blue values.

RED    = (255,   0,   0)
GREEN  = (  0, 255,   0)
BLUE   = (  0,   0, 255)
YELLOW = (255, 255,   0)
BLACK  = (  0,   0,   0)
WHITE  = (255, 255, 255)

For the example above we define RED ( a constant as do not expect the values in the tuple to change) in terms of it’s RGB components.


Check the Answer

Boolean Type

When asking a question it would be good to be able check if the answer given is right or wrong,  but instead of right or wrong Python uses True or False these are stored as a Boolean type. In python console type the following(or download this file and run)

is_correct = False
print(is_correct)
is_correct = True
print(is_correct)
print(type(is_correct))

On the console see the following:

bool_type

Relational Operators

To compare an answer with an expected answer relational operators are used to compare two objects and return a True or False. The objects can be numbers,  strings and booleans. The following are relational operators that are commonly used

  • ==‘  is equal (note difference with assignment operator)
  • !=‘ not equal
  • <‘ less than
  • >‘ greater than
  • <=‘ less than or equal too
  • >=‘ greater than or equal too

In a python console type the following:

answer = 7
answer > 10
answer < 10
answer != 7
answer == 7

On the console see the following:

relational_console

IF/ELIF/ELSE Statement

IF statement gives a program the ability to select if a block of code executes or not based on a condition,  for example using a relational operator. In python a block of code is where a group lines of code have the same minimum level indentation, how far to right the start of the line begins( recommended 4 spaces). Using IDLE create and run a file with the following code for input values 10, 100 and 110. (or download this file and run)

Note: IDLE will indent automatically.

high_score = 100
score = int(input('Input a score:'))
if score > high_score:
    high_score = score
    print('New High Score ', high_score)
print('Your score is ', score)

On the console see the following:

if_only

For the if statement on line 3,  when score is greater than 100 the condition is true and the block of code at lines 4 and 5 runs and displays the new high score. If the score is less than or equal to 100 the block of code at lines 4 and 5 is skipped. Line 6 is outside the block and is always run and displays your score.

Using an else statement gives us the ability to select which of two blocks of code is run based on the condition in the if statement. Using IDLE create and run a file with the following code (or download this file and run):

high_score = 100
score = int(input('Input a score:'))
if score > high_score:
    high_score = score
    print('New High Score ', high_score)
else:
    print('Your score is ', score)

On the console see the following:

if_else

The block of code associated with the else statement is only executed when the condition in the if statement is false. So if the score is less than or equal to than 100 ‘Your score’ is displayed if the score is greater than 100 then ‘New High Score’ is displayed.

We can also use the elif statement to select a single block of code from a number of different conditions. Note that elif is short for else if.

Using IDLE create and run a file with the following code (or download this file and run):

high_score = 100
score = int(input('Input a score:'))
if score > high_score:
    high_score = score
    print('New High Score ', high_score)
elif score == high_score:
    print('Your score equals the high_score of ', high_score)
else:
    print('Your score is ', score)

On the console see the following:

elif

In the above example,

  • the block associated with the if statement(lines 4 and 5) is only executed when score is greater than 100
  • the block associated with the elif statement(line 7) is onky executed when score is equal too 100
  • the block associated with the else statement(line 8) is only executed when all the previous if and elif conditions are False,  in this example when score is less than 100

Note: can have as many elif conditions and blocks as need.

A Quiz Question

The final example shows how to check if a given answer to a question is correct,

Using IDLE create and run a file with the code below (or download this file and run) and input the following:

  • The correct value: Dublin
  • An correct value but using all lowercase characters: dublin

This example shows that checking string values can be difficult as only a small unexpected difference have unexpected results been displayed.

score = 0
city = input('What city is the capital of Ireland? ')
if city == 'Dublin':
    score += 3
    print('Correct')
else:
    score -= 1
    print('Wrong,  Correct answer is Dublin')
print('Your score is ', score)

On the console see the following:

quiz


damian mooney

bits and bytes