Download Develop and verify script language for an algorithm

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Reading: Develop and verify script language for an algorithm
Develop and verify script language for
an algorithm
Inside this reading:
Creating and executing a first script
3
Syntax
5
Reserved words
5
Syntax errors
6
Elements of syntax for Python
Operators
7
7
Syntax for structured programming constructs
11
User input
13
Translating from pseudocode
14
Algorithm 1: Simple sequence and arithmetic operators
14
Algorithm 2: Selection
15
Algorithm 3: Iteration
16
Best practice
17
Summary
840951250
© State of New South Wales, Department of Education and Training 2006
19
1
Reading: Develop and verify script language for an algorithm
840951250
© State of New South Wales, Department of Education and Training 2006
2
Reading: Develop and verify script language for an algorithm
Creating and executing a first script
After you have designed your program using flow charts or pseudocode,
making a script is a two-step process of:
1
Creating your script as a text document using a text editor.
2
Executing the script with the language interpreter.
Note: Windows Notepad is a simple text editor, but it’s much better to use a
programmer’s editor, as they provide features like automatic indentation,
and syntax highlighting. JEdit is an excellent open-source (free)
programmer’s editor.
Let’s go through these steps. Using your text editor, create a one-line script
containing the following code, and save the file with the name given.
Python (hello.py)
print 'Hello World\nBreakfast today is\n\nSpam and Eggs'
Notes

Don’t forget to include the correct file extension (.py for Python). It
is common for Windows Notepad to add the extension ‘.txt’ to the
end of the filename. To prevent this, ensure that the file type in the
save as dialogue box is set to ‘All Files’ before you save the file.

The \n combination represents a special character and instructs
Python to issue a new line in the output.

Python literal strings can be single or double-quoted, there is no
difference, and the sequence ‘\n’ means issue a new line in either
case.
Now we can execute this script. Open to a command prompt on your
operating system to change the directory to where your script is located.
Execute your new script by typing in the interpreter name (python) followed
by the name of the script you just saved. You should see an output similar to
that below.
840951250
© State of New South Wales, Department of Education and Training 2006
3
Reading: Develop and verify script language for an algorithm
Figure 1: Screen showing output
Note that if the interpreter does not run, you need to modify your PATH
environment variable to include the directory where the interpreter is
located.
840951250
© State of New South Wales, Department of Education and Training 2006
4
Reading: Develop and verify script language for an algorithm
Syntax
Syntax is loosely defined as the rules for how the statements fit together in a
language. (Try entering ‘define:syntax’ into http://www.google.com for the
many definitions you’ll find of what the term syntax means.)
The syntax definition of a language provides answers to questions such as:

Where is the end of this statement?

How do I express an IF THEN ELSE construct?

What types of loops are there in this language?

When do I need to use special characters like braces {}, brackets [],
single quotes, double quotes, colons, semi-colons, commas and so
on?

Can I use the word ‘input’ as a variable name?
The syntax of programming languages takes time and practise to learn.
Documentation that accompanies the particular program for a language
defines the syntax of the language. Unfortunately, there is no easy way to
learn to program without having some concept of the syntax of the
language.
An easy way to learn the basic syntax of a language is to learn by example.
The examples used in this reading will only provide you with a starting
point. You should also read the tutorials and user guides for a more
complete introduction to the language.
Reserved words
Programming languages have a set of words that are reserved for certain
actions. Some keywords common to many languages are: if, then, else,
while, for, end, return. Since these words have a special meaning to the
language, we cannot use these words for our own purposes, such as using
them for the name of a variable.
840951250
© State of New South Wales, Department of Education and Training 2006
5
Reading: Develop and verify script language for an algorithm
Syntax errors
Syntax errors result from the incorrect construction or arrangement of code.
They are detected and reported by the interpreter when the code is executed.
When the interpreter finds a syntax error, it stops and outputs an error
message.
Example 1
For example, this line of code has a syntax error:
print 'Hello World
When we try to execute this script, the Python interpreter reports the error.
Figure 2: Syntax error report in Python
The error here is that the text we want to print must be in quote marks. The
above example has a quote mark at the beginning of the text to be output,
but is missing the quote mark at the end.
The Python interpreter reports what type of error it is and shows the line
number in script where the error was detected. A caret symbol (^) points to
where in the line the error was found. (Be aware however that the actual
error may not always be on the line indicated.)
Example 2
The next example shows a syntax error in Python where the ELSE part of an
IF/ELSE construct has been used without first specifying the IF part.
else: print 'I think this is wrong'
Figure 3: Syntax error in Python
840951250
© State of New South Wales, Department of Education and Training 2006
6
Reading: Develop and verify script language for an algorithm
Elements of syntax for Python
In this section you’ll be introduced to some of the elements of syntax for
Python. For more details you should consult the documentation for that
language.
Operators
In programming languages, operators are the symbols that denote operations
to be performed on one or more values. The most commonly used types of
operators include:

Assignment (=)

Arithmetic operators, such as addition.

Comparison operators such as greater-than (>)

Logical operators such as AND, OR and NOT.
Assignment operator
We need to be able to tell the computer to store a value into a variable. To
do this we construct a statement called an assignment statement.
For example, the Python code below is an example of an assignment
statement, which stores the value 15 in the variable named ‘firstNumber’.
The equals sign (=) is called the assignment operator, because it assigns the
value on its right-hand side to the variable on its left-hand side.
firstNumber = 15
The variable called firstNumber would now hold the value 15 until we
assign a new value to the variable or our program exits.
Another example:
c = a + b
Note that assignment is not the same as mathematical equality. In
mathematics, these two expressions really mean the same thing:
c = a + b
a + b = c
840951250
© State of New South Wales, Department of Education and Training 2006
7
Reading: Develop and verify script language for an algorithm
However in programming the second of these expressions is meaningless
(that is, it is a syntax error), because the interpreter cannot know where to
place the value of c.
Arithmetic operators and expressions
Here is a simple example of addition in Python:
c = a + 3
Here, there are two operators: the addition (+) operator, and the assignment
(=) operator. The interpreter adds the value three to the value of a, and
places the result into variable c.
Table 1 below shows the arithmetic operators.
Table 1: Arithmetic operators
Operator Name
Symbol
Example
Result
Addition
+
a=1+2
a has value 3
Subtraction
-
a = 8—2
a has value 6
Multiplication
*
a=4*5
a has value 20
Exponentiation or power
**
a = 2**3
a has value 8
Increment and decrement operators
Often in programming we want to simply add or subtract one. Python
provides a shorthand way to do this using the increment or decrement
operators.
So for example instead of:
a = a + 1
you could simply write:
a++
Or instead of:
a = a – 1
you could write:
a—-
It is a good idea that, until you become proficient in programming, you use
the long form. This is more explicit, and reminds you that you are really
assigning a new value to the variable.
840951250
© State of New South Wales, Department of Education and Training 2006
8
Reading: Develop and verify script language for an algorithm
Order of operations (operator precedence)
When creating mathematical expressions that use a mixture of mathematical
operators, the order in which the calculations are performed is determined
by the precedence of the operators used in the expression. This is the same
as the order of operations in arithmetic.
The result of the example below is that the variable called ‘result’ will be
assigned the value 7, because the multiplication is performed before the
addition.
result = 1 + 2 * 3
Result is 7
By default, the multiplication would be performed first, then the addition.
This is because multiplication has a higher order of precedence than
addition, so it’s done before the addition. To change the order of
precedence, parenthesis () must be used. If you need the addition done first,
enclose the addition operation in parentheses like so:
total = (1 + 2) * 3
In this case the value 9 is stored in the variable ‘total’.
The language reference will document the precedence of all operators. If
you are in doubt, you can always use parentheses to say what you mean. For
example, there is nothing wrong with using parentheses as shown below,
even though the result would have been the same without them:
total = 1 + (2 * 3)
Comparison operators
Comparison operators are used to compare two values and return a true or
false result, as shown in Table 2.
Table 2: Comparison operators in Python
Operator Name
Symbol
Example
Greater-than
>
Less-than
<
Equal to
==
Not equal to
!=
Greater than or equal
to
>=
If a contains
a > 5
If a contains
a < 5
If a contains
a == 3
If a contains
a != 2
If a contains
a >= 5
Less than or equal to
<=
If a contains the value 5
a <= 5
840951250
© State of New South Wales, Department of Education and Training 2006
Result of
comparison
the value 3
false
the value 3
true
the value 3
true
the value 3
true
the value 3
false
true
9
Reading: Develop and verify script language for an algorithm
Comparison operators are usually used in conditions of IF statements or
loops. For example, suppose you need to add 10% to a price (say for tax) if
the price is greater than $100. You would do this using an 'if' statement:
if(price > 100):
price = price * 1.1
Logical operators
Often we need to combine expressions that have true or false values. This
normally arises when we need to combine expressions with comparison
operators. For example, we may wish to program something like the
pseudocode below:
IF humidity > 50 AND temperature > 30 THEN
CALL start_air_conditioner
The ‘AND’ in this pseudocode is a logical operator. The result of the
condition will be true only when humidity is greater than 50 and
temperature is greater than 30. The condition on the left must be true and
the condition on the right must be true for the entire test to be true.
The Python logical operators are AND, OR, and NOT, as shown in Table 3
below.
Table 3: Logical operators in Python
Operator
(pseudocode)
Description
AND
True when
BOTH
operands are
true
OR
NOT
True when
EITHER
operand is
true.
true when
operand is
false
Symbol
Example
and
If x contains the
value 3, and y
contains the
value 2
or
not
x < 5 and y > 3
If x contains the
value 3, and y
contains the
value 2
x < 5 or y > 3
If x contains the
value 3
Result
false
(because y is not
greater than 3)
true
false
not (x == 3)
Additional information for operators for Python can be found in the
reference documents for that program.
840951250
© State of New South Wales, Department of Education and Training 2006
10
Reading: Develop and verify script language for an algorithm
Syntax for structured programming
constructs
You should have encountered the three basic structured programming
constructs of sequence, selection, and iteration. These are quite similar in
most programming languages. We will remind you briefly of the concepts
before describing the syntax.
Sequence
A sequence is simply one or more statements that are to be executed in
order, from top to bottom. For example study this pseudocode sequence that
swaps the content of variables x and y:
SET temp = x
SET x = y
SET y = temp
Note that this sequence only works in the order specified—if you swap the
order, you will not get the desired result.
When coded into a programming language, a sequence of instruction is
known as a block of code. A block of code or statement block can contain
one or many statements.
Block structure
These blocks can be included inside iteration and selection statements. In
Python a set of statements that are indented by the same amount are
considered to be a statement block. Here is an example:
if mark > 82:
print 'Excellent result'
print 'You have achieved a Distinction'
print 'See you next semester'
The two print statements are indented the same amount and are part of the
‘if’ statement. These two statements will only be executed when the
condition (mark > 82) is true. The third print statement is not part of that
block as it has a different level of indentation. This last print statement is at
the same level as the ‘if’ statement itself, and will be executed after the ‘if’
statement.
Notes:

Python is unusual in making the indentation significant. Most
languages (C, Perl, Java, etc.) use brackets to delimit blocks. The
result is that Python code is always indented nicely and has a slightly
simpler syntax.
840951250
© State of New South Wales, Department of Education and Training 2006
11
Reading: Develop and verify script language for an algorithm

There are several ways of indenting code with delimited blocks. We
will use the commonest of these, called the ‘Kernighan and Ritchie’
style (after the designers of the C programming language). See the
Wikipedia article ‘indent style’ at: http://en.wikipedia.org/wiki/.
Selection
Here is the pseudocode for the IF/ELSE statement:
IF test THEN
statement block
ELSE
statement block
ENDIF
Python uses the following syntax for IF/ELSE statements.
if test:
statement block
else:
statement block
Note: the ELSE part is optional, so an IF without and ELSE is syntactically
correct.
if test:
statement block
For example, assuming that we have stored a test mark in a variable called
‘mark’ the code for an IF/ELSE construct that displays PASS or FAIL could
be:
if mark >= 50:
print 'PASS'
else:
print 'FAIL'
When you need to do a series of mutually exclusive tests in pseudocode, you
can string IF statements together using ELSEIF. The syntax for python is
shown below.
if test:
statement block
elif test:
statement block
else:
statement block
Notice that the ELSEIF part is represented by elif in Python.
840951250
© State of New South Wales, Department of Education and Training 2006
12
Reading: Develop and verify script language for an algorithm
Iteration
Let’s look at the syntax of the while loop:
while expression:
statement1
statement2
statement3
Again, the statement block within the while loop is defined by indentation in
Python. The statements within the while loop will be repeatedly executed
until the loop condition becomes false.
User input
All scripting languages provide functions for accepting input from a user
and placing it into variables used in your script. One of these functions will
accept input from the keyboard.
Computer languages often refer to the keyboard as the standard input device
and name it as STDIN. Similarly the computer screen is commonly assigned
as the standard output device and often named STDOUT. Typically,
programming languages use STDIN and STDOUT as the default devices for
the input and output of data.
The statement:
print 'Hello World'
sends the string Hello World to the default output device STDOUT without
being told specifically to send it there. This relieves us of having to always
specify exactly which input or output device to use.
We know how to use the STDOUT device with statements like print ‘Hello
World’, so now we will now look at what we can do with the STDIN device
to accept keyboard input from the operator of our script.
Python provides the raw_input() function for accepting keyboard input. The
function will display the prompt (a string of text to display on the screen to
tell the user what they should input).
This function could be used to request the user’s name like this:
userName = raw_input('what is your name?:')
The user will see the text ‘what is your name’ on the screen, and the
program will wait until the user types an answer and hits the enter key. This
input will be assigned as a string of characters to the variable we called
userName.
We could then display the string with the following greeting:
print 'Hello' + userName + 'what's up'
840951250
© State of New South Wales, Department of Education and Training 2006
13
Reading: Develop and verify script language for an algorithm
Translating from pseudocode
Now let’s write some code based on simple algorithms to see how sequence,
selection and iteration can be expressed in a scripting language such as
Python.
Algorithm 1: Simple sequence and
arithmetic operators
Problem statement: With the two numbers, 10 and 15, perform the basic
mathematical operations of addition, subtraction, division and
multiplication. Display the result of each operation immediately after
performing it.
Pseudocode
Python code
SET num1 = 10
SET num2 = 15
SET result = num1 + num2
DISPLAY result
SET result = num1—num2
DISPLAY result
SET result = num1/num2
DISPLAY result
SET result = num1 * num2
DISPLAY result
num1 = 10
num2 = 15
result = num1 + num2
print result
result = num1—num2
print result
result = num1 * num2
print result
result = num1/num2
print result
Python output
Figure 4: Output screen for Algorithm 1
840951250
© State of New South Wales, Department of Education and Training 2006
14
Reading: Develop and verify script language for an algorithm
For the code line result = num1/num2 Python has performed integer division
of the operands, giving a zero result because 15 divides into 10 zero times
(with 15 remaining). To ensure Python carries out floating-point division,
make one or both of the numbers floating-point, by adding a decimal point:
num1 = 10.0
Algorithm 2: Selection
Problem statement: Create a program to display a student grade according
to the following criteria: A mark that is 50 or more will display a ‘Pass’
message. Any other mark will display a ‘Fail’ message. The mark will be
input from the keyboard and will be a whole number in the range 0 to 100
inclusive.
Pseudocode
READ mark
IF mark >= 50 THEN
DISPLAY Pass
ELSE
DISPLAY Fail
ENDIF
Python code
A first draft of the python code might look like this:
userInput = raw_input('Enter the student mark: ')
if userInput >= 50:
print 'PASS'
else:
print 'FAIL'
Try executing the above script. You will find that the code does not work
correctly—it prints ‘PASS’ for marks below 50. So, what’s happening here?
The problem with the above script is that the IF test is comparing a string of
ASCII characters (userInput) with a number (50). This comparison does not
yield the correct result as a comparison of a string to a number is performed
in terms of the ASCII character set. ASCII 50 in binary is 01100101
01100000, while 50 decimal in binary is 110010.
What we need to do is to convert the string ‘50’ to the number 50.
Fortunately, Python provides a function int() to convert a string to an
integer. So let’s try using it in our script.
userInput = raw_input('Enter the student mark: ')
mark = int(userInput)
if userInput >= 50:
print 'PASS'
else:
print 'FAIL'
840951250
© State of New South Wales, Department of Education and Training 2006
15
Reading: Develop and verify script language for an algorithm
Note: A colon is required following the condition, and following the else
keyword in Python.
Algorithm 3: Iteration
Problem statement: Create a program to accept marks from a user and
display the original mark and the student grade according to the following
criteria. A mark that is 50 or more will display a ‘Pass’ message. Any other
mark will display a ‘Fail’ message. The mark will be input from the
keyboard and will be a whole number in the range 0 to 100 inclusive. The
program is to end when a negative mark is entered.
A loop is required in this case, as multiple marks can be entered.
Pseudocode
SET finished = FALSE
WHILE NOT finished DO
READ mark
IF mark < 0 THEN
SET finished = TRUE
ELSE
IF mark >= 50 THEN
DISPLAY 'PASS'
ELSE
DISPLAY 'FAIL'
ENDIF
ENDIF
ENDWHILE
DISPLAY 'all done'
Python code
finished = False
while not finished:
userInput = raw_input('Enter the student mark: ')
mark = int(userInput)
if mark < 0:
finished = True
else:
if mark >= 50:
print 'Mark entered: ', mark, 'is a PASS'
else:
print 'Mark entered: ', mark, 'is a FAIL'
print 'All done'
840951250
© State of New South Wales, Department of Education and Training 2006
16
Reading: Develop and verify script language for an algorithm
Notes:

We have used the boolean (or ‘logical’) constants ‘True’ and ‘False’
in our Python code. These constants are keywords of the Python
language.

The logical operator not has been used—the loop will continue while
we are ‘not finished’.
Best practice
Best practice in programming is essentially conforming to de-facto
standards agreed upon by members of the programming community. These
standards involve issues such as code layout and documentation styles that
should be used but are not essential for writing scripts.
Indent your code consistently
Python enforces correct indentation because the Python interpreter uses the
indentation to delineate blocks of code.
Naming variables
A good naming style for variables makes readable code. For example:
gstPayable = totalSale * gstTaxRate
balanceDue = totalSale—discount + gstPayable
describes the code better than the following does
x = xx * y
z = xx—yy + x
A few simple rules for variable names are to:

choose meaningful names for your variables; this seemingly trivial
exercise sometimes requires some thought

use all-capitals only for constants, for example ONE_DOZEN

begin the name of a variable with a lowercase character, and begin
any new words with an uppercase character (this is the most popular
convention for variables today) for example, pricePerItem.
840951250
© State of New South Wales, Department of Education and Training 2006
17
Reading: Develop and verify script language for an algorithm
Comments
The comment character is the hatch # symbol. It tells the interpreter to
ignore the text that follows, as the text is merely a comment or note to the
script reader and is not an instruction to execute. It allows you to explain
what the code is supposed to do. Inline comments are used at the end of a
line of code, as follows.
Commenting example
finished = False
# ensure loop entry initially
while not finished:
userInput = raw_input('Enter mark: ')
mark = int(userInput) # get mark as an integer
if mark < 0:
# user is finished
finished = True
else:
# normal case
if mark >= 50:
print 'Mark entered: ', mark, 'is a PASS'
else:
print 'Mark entered: ', mark, 'is a FAIL'
print 'All done'
Your comments should always address the meaning of the code.
Do not simply restate the operation that the code is performing, such as:
if mark < 0:
finished = 1
# mark is less than 0
# assign 1 to finished
Block comments
Block comments appear at the start of a block of code. Their main purpose
is to give a general description of the processing being performed by the
code that follows. They are often placed at the top of a script to relate script
usage, purpose, and revision history. Here is an example:
#-----------------------------------------------------------# Purpose
: Process student test marks
# Description : Accept marks from keyboard and display
#
corresponding grade. Terminates when a
#
negative number is entered.
# Author: Pi Thon
# Date: 10 June 2006
# Version: 1.0.0
#------------------------------------------------------------
840951250
© State of New South Wales, Department of Education and Training 2006
18
Reading: Develop and verify script language for an algorithm
Summary
In this reading we have discussed the two steps of creating and editing a first
script; what syntax is (the language rules for constructing code); and how
syntax errors occur and are reported by the interpreter when the rules of
syntax are broken.
Elements of syntax for the Python programming language were outlined,
including the operators for assignment, mathematical expressions, and those
for logical expressions used in the constructs of iteration and selection.
You learned that translation of algorithm to script code may introduce
syntax errors that need to be corrected before successfully executing the
script, and syntactically correct scripts may still contain logical errors.
A brief overview of best practice in coding was given, including conforming
to coding styles for code indentation, naming of variables and the
convention used for including comments in code.
840951250
© State of New South Wales, Department of Education and Training 2006
19