You are on page 1of 7

Hello World

Table of Contents
Table of Contents
hello, world!

1
2

Displaying Text
Doing Algebra
Mixing Strings and Numbers
Power Up!
A Quick exit

2
3
5
5
6

ST

YL
E

AG

Conclusion

Page 1 of 7

Hello World

hello, world!

We will try out some of these now. The examples will show what you should type
at the >>> Python prompt, along with the result, and the following paragraph
will explain what happens.

AG

Displaying Text

YL
E

The first thing we need to learn is how to get Python to display some
information. Without that, we would not know what the computer had done and
it would all be pretty pointless!
>>> print('hello, world!')
hello, world!

A simple sequence of instructions is the most basic program you can write. The
simplest sequence is one containing a single program statement. A statement is
usually entered all on one line, although occasionally they can spill over onto
two or more lines. A statement is a set of symbols that is meaningful to the
interpreter, its like a sentence in natural language.

The first thing to notice is that you dont need to type the space between the
>>> and the print Python puts that there for you. The part after the >>> is
what you need to type, the second line is the output printed by the interpreter.

ST

Also, Python cares about details like whether or not you use upper or lower case.
If you type Print instead of print , you will get an error because Python
considers the two words to be different. (Some languages are quite strict about
case whereas others are much more forgiving, but its best to just get used to
being very careful about case when programming.)
The print() function is the way to get Python to display its results to you. In this
case it is printing the sequence of characters
h , e , l , l , o , , , , w , o , r , l , d , ! . Such a sequence of characters is known in
programming as a string of characters or a character string or just a plain string.
The characters must be inside parentheses, well discuss the significance of
those later.
You indicate a string by surrounding it in quotes. In Python, you can use either
single quotes (as above) or double quotes: a string. This allows you to include
one type of quote within a string which is surrounded by the other type useful
for apostrophes:
>>> print("I'm a string with a ' in it.")
I'm a string with a ' in it.

Again, some languages are fussy about which types of quotes you can use and
Page 2 of 7

Hello World

where. In such languages, its recommended to stick with double quotes


wherever possible.
Also, its not just characters that can be printed.

Doing Algebra

So straight away, you have a use for Python: its a handy pocket calculator!
Okay, maybe not quite pockety, but you get the point.

subtract, ( - )
multiply, ( * )
divide. ( / )

YL
E

We can also combine multiple expressions like this:

AG

Try a few more calculations. Use some other arithmetic operators like:

Here we have printed the result of an addition we added two and two. Python
recognized the numbers and the plus sign and summed them for us and then
printed the result.

>>> print(((6 * 5) + (7 - 5)) / (7 + 1))


4.0

Notice the way we used parentheses to group the numbers together as we would
naturally do. Python sees this as:

((6 * 5) + (7 - 5)) / (7 + 1)
=> (30 + 2) / 8
=> 32 / 8
=> 4

ST

But, watch what happens if you type the same sequence without the
parentheses:
>>> print(6 * 5 + 7 - 5 / 7 + 1)
37.2857142857

This is because Python will evaluate the multiplication and division before the
addition and subtraction. So, Python sees it as:
(6
=>
=>
=>
=>

>>> print(2 + 2)
4

* 5) + 7 - (5 / 7) + 1
30 + 7 - 0.7143 + 1
37 - 0.7143 + 1
38 - 0.7143
37.2857

This is usually what you would expect, mathematically speaking, but it may not
be what you expect as a programmer! Most programming languages have rules
to determine the sequence of evaluation of operations. This is known as
operator precedence. You will need to look at the reference documentation for
Page 3 of 7

Hello World

each language to see how it works. With Python, its usually what logic and
intuition would suggest, but occasionally it wont be.
As a general rule, its safest to include the parentheses to make sure you get
what you want when dealing with long series of operations like this.
One other thing to note:
>>> print(5 / 2)
2.5

Which is obviously what you would expect. But, if you want to get the whole
numbers, or integers, you can do that by using the floor division sign ( // ) like a
division operator. Python will print the quotient:

>>> print(5 // 2)
2

YL
E

AG

>>> print(5 % 2)
1
>>> print(7 // 4)
1
>>> print(7 % 4)
3

And to get the remainder, we use the modulo operator ( % ):

% is known as the modulo or mod operator and in other languages is often seen
as MOD or something similar. In fact in Python we can get both result (the
quotient) and remainder (modulo) by using the divmod() function:
>>> print(divmod(7,4))
(1, 3)

ST

Experiment and you will soon get the idea. Why bother? Well, it turns out that so
called integer arithmetic is very useful in programming. As a simple example we
can tell whether a number is odd or even by dividing by two and checking
whether the remainder was zero (i.e. it is even) or not (so it must be odd). Like
this:
>>> print(47 % 2)
1

So we know 47 is odd. Now you could probably tell that just by looking at the last
digit, 7. But imagine you were reading the data from a file or a user was typing it
in. Then your program has to figure out whether its odd or even by itself. You,
the programmer, cant help it out by checking visually. Thats one occasion when
modulo ( % ) comes in very handy.
Python has a exponentiation operator ( ** ), too! Exponentiation is when you
raise one number to the power of another. E.g. 23 = 8
>>> print(2 ** 3)
8

Page 4 of 7

Hello World

Mixing Strings and Numbers


>>> print('The total is: ', 23 + 19)
The total is: 42

Youve seen that we can print strings and numbers. Now, we combine both in
one print statement, separating them with a comma. We can extend this feature
by combining it with a useful Python trick for outputting data called a format
string:

AG

In this statement, the format string contains % markers within it. These have
nothing to do with the modulo operator we discussed above, instead they have a
special meaning when used within a string like this. Unfortunately, this double
usage of % means you have to read carefully to determine the context and
therefore what role the % is playing!

>>> print("The sum of %d and %d is: %d" % (7, 35, 7 + 35))


The sum of 7 and 35 is: 42

YL
E

The letter d after the % tells Python that a decimal number should be placed
there. The values to fill in the markers are obtained from the values inside the
parenthesised expression following the % sign on its own. It is important that the
number of values in the final parentheses matches the number of % markers
inside the string. (If any of this sounds confusing, practice a few variations on the
line above and with the information following and it will soon make sense.)
There are other letters that can be placed after the % markers. Some of these
include:
Format String Use
for string

%x

for hexadecimal number

%0.2f

for a real number with a maximum of 2 decimal places


padding the number out to 4 digits with 0s

ST

%04d

%s

The Python documentation gives more of them.


Note:

This style of formatting has been replaced in Python 3 by an even more


powerful (but more complex) style which we will discuss in more detail
in a later topic.

In fact, you can print any Python object with the print function. Sometimes,
though, the result will not be what you hoped for. Perhaps, just a description of
what kind (or type) of object it is. But, you can always print it.

Power Up!
Page 5 of 7

Hello World
>>> import sys

Now this is a strange one. If youve tried it youll see that it apparently does
nothing. But thats not really true. To understand what happened, we need to
look at the architecture of Python.

YL
E

So how do we use these new tools?

AG

In fact, this command makes a whole bunch of new tools available in the shape of
Python functions which are defined in a module called sys. This is how Python is
extended to do all sorts of clever things that are not built in to the basic system.
There are over a hundred modules in the standard library that you get with
Python. You can even create your own modules and import and use them, just
like the modules provided with Python when you installed it. Well learn how to
do that later. There are also many more that you can download from the
internet. Any time you start a new project that is not covered by modules in the
standard library, remember to do a search, there is probably something out
there that can help you.

When you start Python, there are a bunch of functions and commands available
to you called built-ins, because they are, well, built in to the Python core.
However, Python can extend the list of functions available by incorporating
extension modules. Like buying a new tool in your favourite DIY store and
adding it to your tool box. The tool is the sys part and the import operation
puts it into the tool box.

A Quick exit

>>> sys.exit()

Note:

Oops! What happened there? Simply that we executed the exit function
defined in the sys module. That statement causes Python to exit.

ST

Normally, you exit Python by typing the End Of File (EOF) character at
the >>> prompt - CTRL + Z and Enter on Windows or CTRL +
D on *nix systems. In a development tool you exit using the File Exit
menu etc as usual.

Notice that exit had parentheses after it. Thats because exit is a function
defined in sys and when we call a Python function we need to supply the
parentheses even if theres nothing inside them!
If you type sys.exit without the parentheses, Python tells you that exit is a
function rather than executing it!
One final thing is that the last two statements are actually only useful in
combination. That is, to exit from Python other than by typing EOF you need to
type:
>>> import sys
>>> sys.exit()

Page 6 of 7

Hello World

This is a sequence of two statements!

Conclusion
In this chapter, we learned how to:
Display strings,
Display results of arithmetic operations,
Use import to use useful modules

ST

YL
E

AG

That was quite an introduction to programming! But, before we proceed, we


need learn about the ingredients of programming (i.e. data) and how to use it.

Page 7 of 7