Monthly Archives: January 2015

Ask a Question

Show the Question

As well as numbers python can operate on text, called strings. Where a string is just a sequence of characters, in Python the type is named ‘str‘. Below is an example of using a variable to refer to a string. In the Python console type the following

question = 'What is your name? '
print(question)

The quotation mark lets Python know that a string is starting and a closing quotation to end the string. Where both single and double quotations can be used.

question = "What is your age? "
print(age)

When talking about numbers we pictured that the number to be contained within  a box.  For a string we can picture a string as a stack of boxes where each box contains a single character.

string-stack_boxes

Assigning a variable to a string can be pictured as attaching the label to the stack of boxes (not the boxes that contains the characters).

To refer to a single character in a string we use the index number of the box.The index reflects it’s position in the string, where the first character index is 0, second character is 1 and so on. In a Python console type the following ( or download from here)

name = 'Skelly'
print(name)
print(name[0])
print(name[1])
print(name[2])
print(name[5])

Using IDLE to run the code should see the following

name

Rather than depicting these with images an easier way (to draw anyway) is with a diagram like below:

name_dia

Note: In Python there is no type for a single character and each container in a string for a character is a string that contains a single value,  in the Python Console type the following shows the class of the container used to store the first character of ‘Skelly’ is a string (str) itself.

name = 'Skelly'
type(name)
type(name[0])

As with numbers we can perform operations on strings, in a python console type the following:

'Spider' + 'man'
'Ho ' * 3

There is a lot more that can be done with strings in Python,  and these will be explored later as needed, but first exploring how to use python to get an answer.

Get an Answer

After asking a question there needs to be a way to allow the user input an answer, using IDLE create a python file and type in the following code: (or download file from here)

print('What is your name? ')
name = input()
greeting = 'Hello ' + name
print(greeting)
print('"name" refers to a', type(name), end=' ')
print('that contains', name)

Using IDLE to run the code should see the following
hello_you

When running we see that the input function waits for a line to be typed in, and returns the string of characters you typed. In the example above we used the variable ‘name’ to label the returned string containing the characters of the typed in line.

Note: instead of having to print the question we can place the question string in the input function, which reduces the amount of typing to ask a question and get an answer.

name = input('What is your name? ')
print('Hello ' + name)

The string inside the parentheses, (), after input is called the prompt, prompting you that keyboard input is expected at that point.  As the input function returns a string we need to add some more code to convert to an integer (int) or float when we expect the answer to be a number. Add the following code to the Python file created earlier ( or download full program/script from here)

age = input('What age are you? ')
age = int(age)
print('Your age is ', age)
print('"age" refers to a', type(age), end=' ')
print('that contains', age)
# suspicious question next !!!, be careful
# which questions you answer truthfully
money = input('How much money is in your pocket you? ')
money = float(money)
print('You have €', money)
print('"money" refers to a', type(money), end=' ')
print('that contains', money)

Running in IDLE should see

a_bit_personal

Try running the program and type in answers that are not numbers to see what happens !!! (Generally for any program this is a good test as users of a program will always do something different to what the programmer expected. For example when asked age a valid answer is ‘nine’ rather than 9 as expected by the program above.

Advertisements

Python as a Calculator

To use the Python console as a calculator, Open IDLE
StartIDLE_001

In the Python console type the following:

13 + 5
39 - 13
5 * 3
12 / 2
10 % 3

In the Python Console will see the following
cal_000a
As can be seen python preforms the following operations resulting a number (for the  expressions above):

  • +‘ performs addition
  • ‘ performs subtraction
  • *‘ performs multiplication
  • /‘ performs division
  • %‘ performs a modulo operation, returns the remainder after a division

The result of the the division operation result appears different, it has a decimal point
cal_001a
This highlights that Python has two types of numbers,

  • Integers (int), whole numbers sometimes called counting numbers i.e. numbers without fractions
  • Floats (float), any number with a decimal point and are used when when more precision is need. As dollars and euros have cents, meters have centimeters, grams have milligrams a lot of real world measurement units can be divided.

Expressions are not limited to just one operator and can have many, but need to be careful of operator precedence ( i.e. which operators are evaluated first). For example in the following code is the result of the expression on line 1 equal to 16 or 13 and on line 2  equal to 1 or 10

1 + 3*4
12 - 8/4

The result of the expression on line 1 is equal to 13 and on line 2 equal to 10 as  the multiplication and division have a higher precedence than addition and subtraction. For the python operators see here, highest precedence operators are listed first below

  1. *‘, ‘/‘, ‘%‘ (multiplication, division and modulo)
  2. +‘, ‘‘ (addition and subtraction)

Variables

Variables are used by nearly all programs and  give programs a great deal of flexibility. Variables can be used to refer to anything a program needs,  to display,  change or use. The first usage explored here is to use variables is to refer to numbers.

In Python we can  think of variables as labels that refer to a box( or container) that contains a value such as the score in a game, the result of calculation, an answer to a question or even portion of a program that can perform a calculation. Where there are different types of boxes (or containers) such as an integer and float to hold different types of numbers.

Below is an example of a variable that refers to a number used to store the score of a game. In this example the assignment operator(‘=‘ ) is used to label an integer that contains the value:

score = 400294

cal_007

Below is an program  that uses variables to update the score and health of a character in a game. The program also uses a variable to get a value that does not change, i.e. a constant used to add a bonus

In a python console type the following:

BONUS = 10
score = 0
# character fell while climbing a tree
health = 100 - 6
print(health)
# character reached top tree
score = score + 24
# found golden coin in the tree
score = score + BONUS
print(score)
# fell again
health = health - 6
print(health)

Note: The text after ‘#’ is ignored by Python and are comments typically used to explain the meaning of code, also in the code the subtraction of 6 occurs twice where we should use a variable with a meaningful name in these expressions, e.g.

 FALL_PENALTY = 6

The advantage of using a variable is that if we want to change the variable we only need to change it in one place plus it makes the code easier to read,

 health = health - FALL_PENALTY

indicates why health has decreased.

 

cal_003

Up until now we have using the python console which can be slow,

  • Open File, on the IDLE menu press File, then press New File from the drop down menu and a new window will appear
    cal_004
  • Copy or type the code into the new window(Can also download from here)
    cal_005
  • Save file, On the keyboard press CTRL+S or on the menu press File, then Save on the drop down menu and a “Save As” dialog will appear. In the dialog select an location and name for the file with a “py” extension, i.e. example.py
    cal_006
  • Run the script, on the keyboard press F5 or on the menu press Run, then Run Module on the drop down menu
    cal_008
  • On the IDLE Console window will see
    cal_010

The advantage is we run this code as many times and when we like without having to type in all in again. In IDLE press File on the menu, then Open on the drop down menu and a Open Dialog will open which will allow selection of a python file.

Note: To reduce the amount of typing programming languages often have operations that reduce the amount of typing a programmer needs to do to achieve an effect(often these operations are run faster as when a program is executed) in the example code there are two such examples

score = score + 24

can be directly replaced by

score += 24

And

health = health - 4

can be directly replaced by

health -= 4

 

In Python these are called “augmented assignment” operators and as well as addition and subtraction there are multiplication, division and modulo versions as well, i.e.

result = 5
result *= 4
result /= 2
result %= 3

 


PyGame and Python Online Resources

The web has alot of good and bad to help get started with Python and PyGame the following is a collection free online resources that I would call very good

  1. http://programarcadegames.com/, has online videos, labs,  quizes and worksheets
  2. http://inventwithpython.com, a number of online books, (free to download)
  3. http://www.codecademy.com/tracks/python,  Codeacademy python online tutorials

The above sites provide very good guidance on getting started programming with Python and PyGame. Over the next few months the steps needed to program a game will be covered,  but first say hello to python

greeting = "Hello Python!"
print(greeting)

Python + PyGame Install

The following are instructions for a Windows Computer to:

  1. Install Python
  2. Install PyGame
  3. Run a PyGame Example

Note: After should see the following space game

aliens_game

Note also that for Linux the following website has instructions

Install Python

  • Download Python 3.4.2 from https://www.python.org/downloads/
    PythonDownload
  • Run the installer(python-3.4.2.msi) and follow the on screen instructions
  • Press Run Button on the “Open File – Security Question” Dialog for “Do you want to run this file?” question
    pythonsecurityquestion3
  • Press Next button on the “Python 3.4.2 Setup” Dialog for “Select whether …” question
    PythonSetup_001
  • Press Next button on the “Python 3.4.2 Setup” Dialog for “Select Destination Directory” question
    PythonSetup_002
  • Press Next button on the “Python 3.4.2 Setup” Dialog for “Customize Python 3.4.2” question
    PythonSetup_003
  • Press Yes for “User Account Control” Dialog
  • Press Finished button on the “Python 3.4.2 Setup” Dialog for “Complete the Python 3.4.2 Installer” question
    PythonSetup_004

Install PyGame

  • Download PyGame from pygame-1.9.2a0-cp34-none-win32.whl (Now on a Dropbox as link keeps breaking)
  • Copy the file pygame-1.9.2a0-cp34-none-win32.whl to the directory C:\python3.4\Scripts
  • Open a Command Window in the directory C:\python3.4\Scripts
  • In windows Explorer Press Shift Key and the Right button on the mouse
  • Select “Open command window here”
    CommandWindow
  • In the Command Window type “pip3 install pygame-1.9.2a0-cp34-none-win32.whl”
    pygame_install

Run a PyGame Example

  • Using the Windows Start Button, Select “All Programs” and Find the IDLE Python GUI
    StartIDLE_001
  • Double click “IDLE (Python 3.4 GUI – 32 bit)”,  the following screen will appear
    IDLE_PYTHON_CONSOLE
  •  Type in the following command, to check that PyGame is correctly installed:
import pygame
  • Type in the following commands to run an example game, to check that PyGame is working
import pygame.examples.aliens as game
game.main()

IDLE_RUN_PYGAME


damian mooney

bits and bytes