Introductory Programming in Python: Lesson 3
Basic Output

[Prev: Running Python and Python Code] [Course Outline] [Next: Program State and Basic Variables]

The print Statement

The most basic statement in python is "print". The print statement causes whatever follows it to be outputted to the screen. We've already encountered it previously, now it's time to understand how it works. Start up the python interactive shell, and let's explore. Type the following:

Python 2.4.3 (#1, Oct	2 2006, 21:50:13) 
[GCC 3.4.6 (Gentoo 3.4.6-r1, ssp-3.4.5-1.0, pie-8.7.9)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> print 1
1
>>> print 173+92
265
>>> print 173+92.0
265.0
>>> print "hello"
hello
>>>

As one can see, the print statement outputs the value of the expression immediately following it to the screen, and moves to the next line. Note that the third print statement produces slightly different output, namely the extra '.0'. This is because 92.0 and 92 are different to a computer. 92 is an integer, whilst 92.0 is a real number, or in computing terms a floating point number or float for short. The differences will be covered later.

Also of importance is the expression "hello" (note the double quotes). The value of "hello" is hello, and this is what is outputted to the screen by the print statement. hello is designated as a string by enclosing it in quotes. Try to print hello without the quotes and see what happens.

>>> print hello
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
NameError: name 'hello' is not defined
>>>

WTF? Welcome to your first bug! We will soon learn to dissect and understand what all that means, but for the moment it is sufficient to understand that something has gone wrong. But what? Recall from basic concepts we were able to store values in 'labels' or 'variables'. Python consists of a limited set of key words that have special meaning. These key words form the list of atomic statements and expressions that python knows how to handle. Whenever python encounters a word is doesn't recognise, it treats this as a label name. So it obviously doesn't recognise hello as a statement, it thus treats it as a variable. Variables must have a value, because variables are expressions in and of themselves. But we haven't told python what the value of hello is, hence it complains "'hello' is not defined".

The print statement is not so plain and boring as it seems. It can do a few more things that bear mention. Try entering print "Jane has", 7, "apples."

>>> print "Jane has", 7, "apples"
Jane has 7 apples
>>>

Of course we could just as easily use print "Jane has 7 apples" and get the same result. However, separating the number 7 out illustrates two important things about the print statement. Firstly, we can in fact output the values of any number of expressions in a comma separated list, and secondly the outputs of each of the expressions in the comma separated list are separated by a single space each.

Finally, you will notice that the print statement always ends off the line, and starts a new one. Simply leaving a comma on the end prevents this, e.g. print "Enter your name:",. In summary:

Some String Basics

Python treats all text in units called strings. A string is formed by enclosing some text in quotes. Double quotes, or single quotes may be used. There is a small limitation to this however, being that a string cannot be broken across multiple lines.

'this is a string of text'
"this is also a string of text"
'this string will
    cause an error, because it spans multiple lines'

Trying to enter the third string into the interactive shell yields

>>> 'this string will
    File "<stdin>", line 1
            'this string will
                            ^
SyntaxError: EOL while scanning single-quoted string
>>>

EOL meaning End Of Line. If we want to introduce line breaks into strings we can use two methods. The first, and simplest, is to use 'triple quotes' meaning three double or three single quotes to indicate both the beginning and the end of the string, as in

>>> """this string will not
...  cause an error
...    just because it is split over three lines"""
'this string will not\n  cause an error\n    just because it is split over three lines'
>>>

The immediately obvious disadvantage is that everything between the triple quotes is taken as-is, meaning the second and third lines of my string which I indented to line up with the beginning of the first line are indented in the string itself in the form of three spaces after those '\n' thingies. Speaking of which, what the hell are those things? Why does our string contain stuff we didn't put there? Well let's try to print the string out ...

>>> print """this string will not
...    cause an error
...    just because it is split over three lines"""
this string will not
   cause an error
   just because it is split over three lines
>>>

Well the '\n's are gone, but what were they? Strings are sequences of characters and are one dimensional. They have no implicit way to specify a line break, or relative position, or which characters are where relative to which other characters in the string in two dimensions, as displayed on a screen. Hence we get the second method of specifying line breaks within a string. There are special characters known as escape characters which mean special things inside strings. They all start with a backslash '\' which escapes the following character from the string, or in layman's terms means the following character in the string is not a 'normal character' and should be treated specially. Some important escape characters are

\n
line break or New line (n from the n in new line)
\t
tab
\\
a plain backslash

You will see that because a backslash already has a special meaning, namely "treat the next character specially", we can't simply put a backslash into our string. So we escape the backslash with a second backslash, meaning we actually want a backslash and not a special character.

Finally, how do we actually put quotes inside a string since they indicate the end of a string. The easiest solution is to mix your quotes. If you want a single quote in a string, define the string with double quotes, e.g. "I've got this escape thing all figured out!". Alternatively, you can actually escape quotes within strings, to give them the special meaning that they don't end the string, e.g. 'I\'ve got this escaped thing totally figured out!'

Exercises

  1. What does the print statement do generally?
  2. Start the python interactive interpreter:
    1. Output your first name.
    2. Output your surname.
    3. Output your first name followed by a space followed by your surname.
    4. Create a variable called 'firstname' and put your first name into it.
    5. Create a variable called 'surname' and put your surname into it.
    6. Using only the variables you have created, print your first name and surname again, making sure there is exactly one space between your two names.
    Quit the python interactive interpreter.
  3. What special rules does the print statement adhere to regarding trailing spaces and newlines?

Consider the following code...

print "MUCH madness is divinest sense,"
print "To a discerning eye;"
print "Much sense the starkest madness."
print "'T is the majority", "In this, as all, prevails."
print "Assent, and you are sane;"
print "Demur,-you're straightway dangerous",
print
print "And handled with a chain."
  1. What output, exactly, does the above code produce? Indicate space with underscores.
  2. Write a program that prints "Hello".
  3. Write a program that outputs favourite piece of poetry or other prose, over multiple lines.
  4. How can you print a value stored in the variable 'x'?
  5. How can you print the values of multiple expressions on one line?
  6. Write a program that outputs your name, age, and height in metres in the following format. Make sure age is an integer, and height is a float, and not simply part of your string.
    My name is James, I am 30 years old and 1.78 metres tall.
  7. Explain three possible ways to print a string containing an apostrophe, for example the string
    The cat's mat.
[Prev: Running Python and Python Code] [Course Outline] [Next: Program State and Basic Variables]