Jump To Content

LearnHub




Python - The Basics

Introduction

Two things determine how long a solution takes
  1. How long it takes to write the solution (human time)
  2. How long it takes for that solution to run (computer time)

Different languages make different trade-offs between those two choices; higher level languages let people express their ideas quickly, but the more abstract the language, the slower the execution.

This lesson is the first in a series of lessons on Python; a nimble scripting language the is
  • available on most platforms; for free (get it now from the official python website)
  • widely used and well documented
  • easy to learn
In the expression vs. speed decision, Python has decided to make it really easy to express your ideas, but it is the wrong solution to a performance intensive problem.

Running Python Programs

The lack of blinding speed, but agility is largely due to Python being an interpreted language. The other type of language is a compiled one, like C or Java. It is always handy to know what your program is doing when you run it. Before getting into the basics of Python, let's look at how programs get executed.

Compiled languages have a 2-stage execution cycle
  1. The compiler transforms the human readable source code into machine specific code
  2. The application is then run on top of the operating system (in the case of C/C++) or virtual machine (as in Java)
Interpreted languages combine these 2 stages
  1. The interpreter loads the source code, translates (compiles) it into a more compact form -- if necessary, and executes it

The extra compilation phase gives the computer a chance to optimize what is finally executed but creates an extra hurdle in giving rapid feedback to the user. Rapid feedback is an important characteristic of load-and-go, interpreted languages.

You can run Python programs in 3 ways
  • Interactively by just typing python (if it is on your PATH)
$ python
Python 2.4.4 (#1, Dec 15 2007, 17:25:59)
[GCC 4.1.1 (Gentoo 4.1.1-r3)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> print 1+4
5
>>> ^D
$
    • The >>> is the Python interactive prompt
    • ^D is not actually typed to end you session, instead you type control-D which is Unix for "end of file"
  • By passing a Python file to the interpreter
$ cat five.py
print 1+4
$ python five.py
5
$
  • Including an execution shortcut at the beginning of your Python file and running it directly. An execution shortcut tells the Unix Shell which application to choose when running the program. Because it begins with #! the common way to refer to this is hash-bang or shebang. (Remember to make the file executable)
$ which python
/usr/bin/python
$ chmod a+x five.py
$ cat five.py
#!/usr/bin/python

print 1+4
$ ./five.py
5
$

One last thing to mention about how things get run in Python is how to prevent certain parts of your program from being run which is accomplished through the use of a comment. Comments are ignored by the interpretor and not get executed. You indicate that something is a comment by putting a # in front of it; everything from that point to the end of the line is a comment.

>>> # this is a comment
...
>>>

Unlike other languages, Python does not support multi-line comments like C or C++.

Variables

A variable is just a name for a value. Variable in Python created whenever something is assigned to them through the use of a single = which is called the assignment operator.

>>> planet = "Pluto"
>>> moon = "Charon"
>>> p = planet

This speeds up programs generation because you do not have to remember to declare variables before assigning a value to them. This means thought that you have to remember to create them before using them though as there is no default value.

>>> planet = "Sedna"
>>> print plant # note the misspelling of the variable name
Traceback (most recent call last):
File "<stdin>", line 1, in ?
NameError: name 'plant' is not defined

Unlike languages like C or Java, variables in Python are untyped which means that a single variable can refer to different types of values at different times. Don't abuse this ability though; the readability of your code might suffer.

>>> planet = "Pluto"
>>> moon = "Charon"
>>> p = planet
>>> planet = 9

Variable values are typed however
>>> x = "two" # "two" is a string
>>> y = 2 # 2 is an integer
>>> print x * y # multiplying a string concatenates it repeatedly
twotwo
>>> print x + y # but you cannot add an integer and a string
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: cannot concatenate 'str' and 'int' objects

Printing

The print statement prints one or more values to standard output (separated by spaces) and unlike C's sprintf includes its own newline character. To suppress this automatic newline, put a comma ( , ) at the end of the line

$ cat charon.py
#!/usr/bin/python
planet = "Pluto"
num_moons = 1
moon = "Charon"
print planet, "has", num_moons, "satellite",
print "and its name is", moon
$ ./charon.py
Pluto has 1 satellite and its name is Charon

Creating Strings

Strings are discussed in greater depth in another lesson, but since we have used a number of them already it is worth explaining how they are created.

A string is created whenever a variable's value begins with either a single quote ( ' ) or double quote ( " ). You can include both types of quotes in the string, but it must being and end with the same kinds. Which type you use in your program is a matter of personal style.

>>> print "He said, \"It ain't what you know, it's what you can.\""
He said, "It ain't what you know, it's what you can."

Sometimes the value you want to store is too long for the standard screen size. To create a multi-line string, you use triple quotes (of either kind).

$ cat sedna.py
#!/usr/bin/python
print "Sedna was discovered in 2004"
print 'It takes 10,500 years to circle the sun.'
print '''The tiny world may be part of the Oort Cloud,
a shell of icy proto-comets left over from
the formation of the Solar System.'''
$ ./sedna.py
Sedna was discovered in 2004
It takes 10,500 years to circle the sun.
The tiny world may be part of the Oort Cloud,
a shell of icy proto-comets left over from
the formation of the Solar System.

Escape Sequences

Escape sequences snuck into the last section when illustrating using a " in a string that begins and ends with a ". Escape sequences are you how embed certain special characters into a string that cannot be represented in another way. The format for these is a \ followed by a specific character
  • \\ - backslash
  • \' - single quote
  • \" - double quote
  • \b - backspace
  • \n - newline
  • \r - carriage return
  • \t -tab
Of these, you will most often use \t and \n.

Casting

The process of converting a variable value from one type to another is called casting. Python has a number of built-in functions to do this for each type. The most common ones you will use are
  • str
>>> print "Diameter: " + str(1280) + "-" + str(1760) + " km"
Diameter: 1280-1760 km
  • int
>>> print int(12.3)
12
  • float
>>> print float(4)
4.0

Numbers

As with most programming languages, there are a number of kinds of a number in Python. The two main ones are Integrer and Float:
  • Integer
    • No decimal point
    • Positive or negative
    • 32 bits long (on most machines)
>>> i = 14
>>> print i
14
  • Float
    • Has a decimal point
    • 64 bits long
>>> f = 14.0
>>> print f
14.0

Less commonly used are Complex (1+4j) and Long Integer (14L), but you should be aware of their existence.

Arithmetic

Python borrows C's arithmetic operators. Interestingly you can use them on numbers as well as strings
  • Addition
>>> print 35 + 22
57
>>> print 'Py' + 'thon'
Python
  • Subtraction
>>> print 35 - 22
13
  • Multiplication
>>> print 3 * 2
6
>>> print 'Py' * 2
PyPy
  • Division
>>> print 3.0 / 2
1.5
>>> print 3 / 2
1
Note how integer division rounds down
  • Exponentiation
>>> print 2 ** 3
8
  • Remainder
>>> print 13 % 5
3

Truth

There are a number of ways that Python can decide whether some statement or test evaluates to being True or False. At the most basic level empty strings and 0 are considered to be false with (almost) everything else being true. (If you cannot remember that, you can make use of the Boolean type. Booleans are a built-in type like strings or integers, and have the values True or False.)

The notion of True and False is at the very center of Python's ability to make decisions.

With numbers, you determine truth as follows
  • a == b - the value of a is the same as the value of b.
  • a != b - the value of a is different than the value of b
  • a > b - the value of a is more than the value of b
  • a < b - the value of a is less than b
  • a >= b - the value of a is equal or greater than the value of b
  • a <= b - the value of a is equal or lesser than the value of b
Strings use the same operators and evaluates one character at a time until a False condition is met or there are no more characters to compare. One thing to remember when comparing strings is the order things are evaluated in: numbers, uppercase letters, lowercase letters.
  • 'abc' == 'Abc' - False
  • 'ab' < 'abc - True
  • '100' < '2' - True
One powerful technique when determining truth is to combine tests with a short-circuit operator. Python has two of these: and, or. They are called short-circuit operators because they evaluate from left-to-right and as soon as an answer is determined, evaluation stops and returns the result.


Decision Making

Now that we know how to determine whether something is true or not, we can make a decision based upon it. This is best illustrated with an example.

#!/usr/bin/python
a = 3
if a < 0:
print 'less'
elif a == 0:
print 'equal'
else:
print 'greater'

To walk through the code, this is what the interpreter is doing
  • set the integer value of 3 to the variable a
  • check whether a (3) is less than 0 and since it is not, continue checking for truth
  • check whether a (3) is equal to 0 and since it is not, continue checking for truth
  • since there are no more checks, execute the commands inside the nested block (indicated by the : )
You can have as many elif's as you want, but it must begin with an if. Both elif and else are both optional.

$ ./decision.py

greater

Indentation?

The decision example is the first time Python's indentation rules have been shown. Unlike other languages which use { and } (like Java) or 'begin' and 'end' (like PL\SQL) to indicate blocks of code, Python uses whitespace.

This is the part that people used to the other methods say to themselves "What?!?!".

Studies have shown that indentation, not the placement of the markers like { and } is what people use to read code. There are some rules though
  • Everything in the block must be indented the same amount
  • Both spaces and tabs are acceptable, but spaces are the more preferred method
  • By convention, 4 spaces are used to indicate a single indentation amount

Over and over. And over. And over...

Sometimes you want to keep doing something as long as some condition is true. The while loop is Python's way of doing just that.

$ cat disappearing_moons.py
#!/usr/bin/python
num_moons = 3
while num_moons > 0:
print num_moons
num_moons = num_moons - 1
$ ./disappearing_moons.py
3
2
1

You can see from the example that the structure of the while loop is very similar to that of the if. This type of loop is quite handy when waiting for certain other events or processes to complete before execution continues. They can however result in infinite loops that never end. Two possible preventative measures against infinite loops are break and continue.

In this example, the while loop is infinite since True is always true, but break is used to exit the loop.

num_moons = 3
while True:
print num_moons
num_moons = num_moons - 1
if num_moons <= 1:
break

Also illustrated is how indentation works when nested. While break stops execution of the loop entirely, continue stops only the current iteration of the loop and goes back to the truth test at the top.

$ cat continuing.py
#!/usr/bin/python
num_moons = 5
while num_moons > 0:
print 'top:', num_moons
num_moons -= 1
if (num_moons % 2) == 0:
continue
print '...bottom:', num_moons
$ ./continuing.py
top: 5
top: 4
...bottom: 3
top: 3
top: 2
...bottom: 1
top: 1

break and continue should be used sparingly. It is almost always a better idea to have an appropriate truth test at the start of your while loop.

Formatting

Even the smallest script often needs to communicate its results to the user and most of the time the text is dynamic. They way you build and format output in Python is through the use of the % operator. Format operators come in pairs (or sets of pairs). Inside the string is the indication of how things are to be formatted and outside of the string is the value (or values -- in ()'s separated by ,).
  • 'here %s go' % 'we' creates here we go
  • 'left %d right %d' % (-1, 1) creates left -1 right 1
This example pads the number given with with 0s until the whole number is 4 digits in length
  • '%04d' % 13 creates 0013
There are a number of different formats you can use, but as is often the case there are a couple you will likely use more often. For the rest, see the String Formatting Operations page in the Python documentation.
  • %d - an integer
  • %f - a float
  • %s - a string
Summary
This lesson introduced you to the Python language and some of its basic building blocks and syntax. Using
  • strings
  • number
  • decisions using if
  • while loops
  • and formatted output
you can accomplish a great deal. The next couple lessons will build directly on this foundation to give you a firm grounding in this rich



Your Comment
Textile is Enabled (View Reference)