Chapter 6 of the textbook gives an overview of traditional concepts for high-level programming languages. To make those concepts more tangible, we will practice using a high-level language known as Python. The rest of these notes give a very brief overview of the language, using the terminology of our text book. 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.
You may write and execute your own Python programs online at http://cs.slu.edu/~goldwasser/demos/python. For more serious programming, Python is freely available and can be installed on all major computing platforms.
Python has support for handling many types of data, including the following.
| type | explanation |
|---|---|
| int | integer value |
| float | floating point value (not necessarily integral) |
| str | a character string |
| bool | A logical truth value |
There are actualy many other types, but we will focus just on these few.
Besides those basic data types, there is support for representing more intricate data structures which conceptuatlly combine many pieces of data into one view. For example there is a list class which can be used to manage an arbitrary list of values. Also, a program is free to defining additional classes of data which suit the needs of a particular piece of software.
Python determines data types dynamically; the type does not need to be explicitly declared. Instead the context is used to determine the intended type.
For the primitive data types, there are forms known as literals. Examples are given in third column of the following table.
| type | explanation | literals |
|---|---|---|
| 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?" |
| bool | A logical truth value | True False |
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. The general form of an assignment
looks like
x = 5
Once this assignment is made, the identifier on the left-hand side is
associated with the value expressed on the right-hand side. The value
on the right-hand side can either be expressed as a literal, as
discussed earlier, or described using something we call an expression.
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, the most commonly used operators are the following
| 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 programs:
x = 17/3
print x
y = 17%3
print y
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:
a = 17.0/3.0
print a
b = 17/3
print b
c = 17%3
print c
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:
greeting = "Hello. "+"How are you?"
print greeting
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:
foo = 17+2
print foo
bar = "17"+"2"
print bar
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) |
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
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"
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 raw_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 = raw_input()
You can provide a prompt for the user either with a
preliminary print statement, or by specifing the prompt as a
parameter to the raw_input statement, as in:
person = raw_input("Please enter your name: ")
The result of this function is always a string, representing the precise characters that the user typed before hitting the enter key.
If you are expecting the user to enter some other data type, such as a
number, you must explicitly convert it to that data type. This is
done with a syntax such as the following:
celsius = float(raw_input("Enter the temperature in celsius: "))
fahrenheit = celsius * 9.0 / 5.0 + 32
print "The temperature (in fahrenheit) is: ", fahrenheit
You can express a conditional statement, such as in the following
example to calculate the absolute value of an input value:
value = int( raw_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 = int(raw_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 = float(raw_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.0
value = float(raw_input("Enter a number: "))
while value!=0:
sum = sum + value
value = float(raw_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 = float(raw_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
number = float(raw_input("Enter a number: "))
print absolute(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: