To gain experience in programming in a high-level language, we will rely on a language named Python. You may write and execute your own Python programs online at http://cs.slu.edu/~goldwasser/demos/python, as demonstrated during class.
The remainder of this document is meant to provide you with an introductory tutorial to the language. We will in no way cover the full Python language, but enough of it to do a few interesting things. Those wishing to dig deeper can go to the official Python website for more information.
Before we explore the various instructions which can be given in Python, we point out that it is often convenient to put comments into a program which are ignored by the language, but helpful to a human who may be reading the program. In python, the character # generally designates that the rest of a given line is meant as a comment.
For example, the following program does not do anything at all.
# this is a comment, nothing happens here
In the following program, the comment is from the # sign
until the end of the line, but the beginning of the line is a
legitimate instruction.
print "Hello" # this program really prints "Hello"
Python has support for handling many types of data. We will rely on a few of the primitive data types:
| type | explanation | examples |
|---|---|---|
| int | integer value | 35 -231 007 |
| float | floating point value (not necessarily integral) |
35.3096 -3.14159 5.000 |
| str | a character string | "Welcome." 'Welcome' "Hello, who's there?" |
Note that types are determined implicitly in Python; they need not be explicitly declared. Context is generally used to determine the intended type.
There are several operators which can be used to build more complex expressions based upon the underlying data. What operators are available depends on the data type.
For integers you may use the following five operators:
| operator | semantics | example |
|---|---|---|
| + | addition | 3+4 |
| - | subtraction | 8 - 2 |
| * | multplication | 23*4 |
| / | quotient of division | 17/3 |
| % | remainder of division | 17%3 |
Note carefully the existence of two separate operators for an integer
divsion, one which returns the resulting quotient and one which
returns the resulting remainder. To see them in action, try
executing the following simply Python program:
print 17/3
print 17%3
For floating point numbers, you may use the following four operators:
| operator | semantics | example |
|---|---|---|
| + | addition | 3+4 |
| - | subtraction | 8 - 2 |
| * | multplication | 23*4 |
| / | division | 17.0/3.0 |
Again, note carefully the behavior of division when dealing with
floating point data, rather than integers. Let's update our previous
program to read:
print 17.0/3.0
print 17/3
print 17%3
There are many ways to manipulate characters strings, though we will
not examine most of the techniques. One very useful one, however, is
that two strings can be concatenated using the +
operator. For example, you may do the following, if you wish:
print "Hello. "+"How are you?"
To get the resulting string "Hello. How are you?". Note
carefully that the space after the period was explicitly included in
the first of the original operands.
If you wish, you can even use the * operator on strings, where "Hello"*6 is interpretted to be the string "Hello" concatenated with itself, six times, resulting in "HelloHelloHelloHelloHelloHello".
But be very careful about mixing types. For example, with integers,
17+2 will evaluate to 19, but with strings,
"17"+"2" will be concatenated to "172", as shown if
executing the following code:
print 17+2
print "17"+"2"
We can create a boolean expression by comparing two pieces of data from some other type, using a relational operator, such as:
| operator | semantics |
|---|---|
| < | less than |
| <= | less than or equal to |
| > | greater than |
| >= | greater than or equal to |
| == | equal to |
| != | not equal to |
We can then form compound boolean expressions using the logical operators:
| operator | semantics | example |
|---|---|---|
| and | logical 'and' | x==4 and y>3 |
| or | logical 'or' | x==4 or y>3 |
| not | unary negation | not (x==4 or y>3) |
Any time you wish to introduce a variable to store a piece of information, you are free to do so. You may generally pick any "identifying name" that you wish for the variable (the only exceptions are that certain identifiers are reserved words in the language, such as print).
Storing information is done using the = symbol, which is
known as the assignment operator. Recall that in syntax, such as
<variable> = <expression>, the right-hand-side
expression is first evaluated, and its result is then stored
associated with the left-hand-side variable. Can you predict the
result of the following program?
x = 5
x = 10*x + 3
print x
How about this one?
x = 5
y = 2*x
z = y + 4
x = 2*z - y
y = x+1
print x
print y
print z
If using strings in such statements, please be advised that the system
must distinguish between your identifier names and intended string
literals. It does so by making sure that string literals are enclosed
in quotation marks (your choice of single or double quotes). For
example, the following is legal:
greeting = "Hello"
print greeting
However, look carefully at what happens when executing the following:
welcome = "Hello"
print "welcome"
or the following
welcome = Hello
print welcome
We do have a way to get input from the user or to display output to the user. Let's start by examining output, since we've already seen examples of this.
You may use the print command to generate textual output for
your program. If you print a literal value, such as:
print 6
print "Hello"
The literal value is displayed.
If the operand is a complex expression, it is first evaluated by
Python, and then only the result is displayed, such as with the
earlier example:
print 17.0/3.0
print 17/3
print 17%3
If you specify a variable name, the
associated data will be printed, as with
print x
print greeting
though this can only be done when you have previously assigned some
data to the variable.
Finally, we note that a newline character is automatically
included in the output, by default. If you wish to print several
pieces of information on a single line, you may do so by separating
them with commas, in which case they will appear on the same line,
separated by a single space. An example follows:
greeting = "Hello"
x = 5
print greeting,x
If you wish to intentionally print out a line of output but without
a newline character, you may do so by putting a comma at the end
of the statement, as with:
greeting = "Hello"
print greeting,
Alternatively, if you wish to produce a newline but do not wish to
display an operands, you use the syntax:
print
If you wish to read a line of input from the user, you do so using the
command input(). Of course if you wish to save the value,
you will probably wish to use this command in the right-hand side of
an assignment expression, such as:
x = input()
How user is entered by the user depends on the environment. For our
software, there is a single line entry which will be highlighted in
yellow when input is requested. The user should enter the input
characters into the yellow box and press the return key to
enter the data.
Of course, you'd have to assume that the user knew what type of input
you were expecting (e.g., characters, numbers, etc), and how you would
be using it. You can provide a prompt for the user either with a
preliminary print statement, or by specifing the prompt as a
parameter to the input statement, as in:
celsius = input("Enter the temperature (in celsius): ")
fahrenheit = celsius * 9.0 / 5.0 + 32
print "The temperature (in fahrenheit) is: ",fahrenheit
If the input is intended to be a name, such as in:
name = input("Please enter your name: ")
The user must use quotation marks when entering the response
(e.g. "Michael" not Michael)
You can express a conditional statement, such as in the following
example to calculate the absolute value of an input value:
value = input("Enter a number: ")
if value<0:
value = -value
print "The absolute value is ",value
We wish to point out several important aspects of the above syntax.
The conditional statement takes the general form,
if expression:Note that the expression can be an arbitrary boolean expression. There is a colon to designate the end of the expression. The body of the conditional must be indented. If you wish to have the conditional body which is more than one statement, simply continue to indent (using precisely the same amount of indentation) as long as the conditional body is to continue. When you wish to end the conditional body, and resume the remainder of the program, simply go back to the previous level of indentation, as in:
body
rest of program
value = input("Enter a number: ")
if value<0:
value = -value
print "You entered a negative number"
print "The absolute value is ",value
A conditional can also include an else clause, such as in the
following:
temp = input("Enter temperature: ")
if temp > 75:
print "No jacket is necessary"
else:
print "A light jacket is appropriate"
print "Goodbye"
The general format of a while loop is:
while expression:
body
rest of program
For example, the following count-controlled loop prints out numbers
from 1 to 10:
count = 1
while count <= 10:
print count
count = count+1
As another example, the following event-controlled loop computes the
sum of user-entered numbers, where the user enters 0 to designate the
end.
sum = 0
value = input("Enter a number: ")
while value!=0:
sum = sum + value
value = input("Enter a number: ")
print sum
Careful: if you write code which enters an infinite loop, you will never regain control (and will likely need to restart your browser).
Thus far, we have seen examples where the body of a conditional statement was a single instructions or a series of instructions. Similarly, we have seen how the body of a loop can be a series of instructions. In fact, such bodies can themselves be arbitrarily complex code fragements, perhaps including the nesting of further control structures.
For example, here is a program which has a conditional statement,
nested within the body of a previous conditional statement:
temp = input("Enter temperature: ")
if temp > 75:
print "No jacket is necessary"
else:
if temp < 40:
print "A heavy jacket is appropriate"
else:
print "A light jacket is appropriate"
print "Goodbye"
Here is an example of a program which uses a conditional statement,
nested within a loop, to print out all odd numbers
between 1 and 20 (inclusive):
count = 1
while count <= 20:
# we only want to print odd numbers
if (count%2)==1: # odd numbers are those with remainder of 1
print count
count = count + 1
We can even put another loop within the body of a loop, such as the
following program:
row = 1
while row<=10 :
# print out 'row' asterisks in this row
column = 1
while column<=row:
print "*", # the comma ensures that no newline is produced
column = column + 1
print # this print will generate a final newline for the row
row = row + 1
# we're done!
Which produces the following lovely output:
*
* *
* * *
* * * *
* * * * *
* * * * * *
* * * * * * *
* * * * * * * *
* * * * * * * * *
* * * * * * * * * *
To define a subprogram, use the def keyword, giving the name
of the subprogram, followed by parentheses, then the indented body of
the subprogram. Here is an example:
def Chorus():
print "Lucy in the sky with diamonds"
print "Lucy in the sky with diamonds"
print "Ahhh..."
Pleae notice that running the above program does not produce any
result. The subprogram is being defined, but not executed. To
invoke the subprogram, we would first need to define it and then to
use the command Chorus(), as in the following example:
def Chorus():
print "Lucy in the sky with diamonds"
print "Lucy in the sky with diamonds"
print "Ahhh..."
print "Picture yourself in a boat"
print "..."
Chorus()
print
print "Follow her down to a bridge..."
Chorus()
print
print "Picture yourself on a train..."
You may notice in the preceding example that parentheses were required
after the identifier name when defining a subprogram. These are used
to specify the necessary parameters to the subprogram. In the above
Chorus() subprogram, there were no parameters. In the
following example, we will see how a formal parameter name is
used within the subprogram body, and how an actual parameter such as
"Michael" is used when invoking the subprogram:
def Sing(name):
print "Happy Birthday to you."
print "Happy Birthday to you."
print "Happy Birthday dear",name
print "Happy Birthday to you."
print
Sing("Michael")
Sing("Susan")
In fact, in the above we may wish to reduce the repetitiveness of the
"Happy Birthday to you." statements. We can do so by having a
subprogram which itself invokes another subprogram, as follows:
def happy():
print "Happy Birthday to you."
def Sing(name):
happy()
happy()
print "Happy Birthday dear",name
happy()
print
Sing("Michael")
Sing("Susan")
Parameters are used to send information from the "caller" of a subprogram, to the subprogram itself. At times, we may wish to pass resulting information from the subprogram, back to the caller. We may use the command return at the end of a subroutine to do so.
For example, we earlier looked at program that
calculated the absolute value directly. We might want to define
this as a subroutine, so that we could reuse it. Such a subroutine
could take an intial value as a parameter, and return the absolute
value of that parameter as the result. The syntax for such a
subprogram, as well as its use, follows:
# this defines a new subprogram
def absolute(value):
if value<0:
value = -value
return value
# and this continuation demonstrates its use, by asking the user for
# numbers, and converting them to their absolute value (quitting when
# the user enters zero).
number = input("Enter a number: ")
while number!=0:
print absolute(number)
number = input("Enter a number: ")
For the remainder of the time, we use the above techniques, working as a group to develop some new programs for a variety of tasks, such as: