Strengths
Python is flexible, like the shell, but also makes use of more data structures, so not everything needs to be squeezed into lists of strings. Python is freely available on many platforms, and is widely used and well documented. It is much easier to learn and read than Perl!
Weaknesses
Nimble languages like Python are slower than sturdy languages like Fortran, C/C++, or Java, often by a factor of 20. On the other hand, it's relatively easy to call libraries in those other languages from Python. Python doesn't have as many numerical or statistical tools as MATLAB, but its does have some. Its not used as widely as Perl right now, but it's catching up.
Execution Cycle
Sturdy languages use a two-step execution cycle:
- Compile source code (put machine-oriented form in file)
- Run the contents of that file on top of an operating system or virtual machine
Nimble languages combine these two steps:
- Compiler and virtual machine are the same program
- Load source code, translate into more compact form if necessary, and execute
![sturdy_vs_nimble.png sturdy_vs_nimble.png]()
This is why sturdy programs run faster, but nimble programs are faster to write. Compiling gives the computer a chance to optimize, whereas "load-and-go" makes human turnaround faster.
Running Python Programs
You can run it interactively, like the shell:
$ python
Python 2.4.2 (#67, Sep 28 2005, 12:41:11) [MSC v.1310 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> print 124/28
4
>>> print 124.0/28.0
4.4285714285714288
>>> ^D
"^D" represents control-D, which is Unix's way of saying “end of input”.
Obviously, you don't have to retype program every time you want to run it. If you save a program in a file with a .py extension, and type python filename.py:
$ cat saved.py
print 124/28
print 124.0/28.0
$ python saved.py
4
4.42857142857
Execution Shortcuts
On Unix, if you make #!/usr/bin/python the first line of the program, this tells Unix to execute /usr/bin/python and use the rest of the file as input. Of course, this doesn't work if Python is installed somewhere else, so use which python to find out.
Or, even better, use #!/usr/bin/env python as the first line, since this tells Unix to use /usr/bin/env to find Python, then run the script with it:
$ cat hashbang.py
#!/usr/bin/env python
print 124/28
print 124.0/28.0
$ hashbang.py
4
4.42857142857
On Windows, you have to associate .py files with Python (this happens automatically when you run the Python Windows installer), so then double-clicking on anything ending in .py will run it automatically.
Variables
Variables are just names for values. There are no declarations - variables are created when something is assigned to them:
planet = "Pluto"
moon = "Charon"
p = planet
Python also has no types: a variable is just a name, and can refer to different types of values at different times
planet = "Pluto"
moon = "Charon"
p = planet
planet = 9
Your code will be easier to understand if you don't abuse this fact.
Possible Mistakes
You must give a variable a value before using it
planet = "Sedna"
print plant # note the misspelling
Traceback (most recent call last):
File "lec/inc/py01/undefined_var.py", line 2, in ?
print plant # note the misspelling
NameError: name 'plant' is not defined
Unlike some languages, Python doesn't provide a default value because doing so can hide a lot of errors. (Note: anything from "#" to the end of the line is a comment).
Variables don't have types, but values do. Python complains if you try to operate on incompatible values:
x = "two" # "two" is a string
y = 2 # 2 is an integer
print x * y # multiplying a string concatenates it repeatedly
print x + y # but you can't add an integer and a string
twotwo
Traceback (most recent call last):
File "lec/inc/py01/add_int_str.py", line 4, in ?
print x + y # but you can't add an integer and a string
TypeError: cannot concatenate 'str' and 'int' objects
Printing
The print statement prints zero or more values to standard output, separated by spaces. It automatically puts a newline at the end, so print on its own just prints a blank line. Putting a comma at the end of the line suppresses the newline
planet = "Pluto"
num_moons = 1
moon = "Charon"
print planet, "has", num_moons, "satellite",
print "and its name is", moon
Pluto has 1 satellite and its name is Charon
Quoting
You can use either single or double quotes to create strings, but each string must start and end with the same kind of quote. Different strings in the same program can use different kinds of quotes. Use triple quotes (of either kind) to create a multi-line string:
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.'''
Converting Values to Strings
The built-in function str converts things to strings:
print "Diameter: " + str(1280) + "-" + str(1760) + " km"
Diameter: 1280-1760 km
Use int, float, etc. to convert values to other types:
print int(12.3)
12
print float(4)
4.0
Numbers
14 is an integer (32 bits long on most machines)
14.0 is double-precision floating point (64 bits long)
1+4j is a complex number (two 64-bit values) - use x.real and x.imag to get the real and imaginary parts
123456789L is a long integer
- Arbitrary length: uses as much memory as it needs to
- Operations are several times slower
Arithmetic
Python borrows C's numeric operators, and also adds ** for exponentiation.
Name Operator Use Value
Addition + 35 + 22 57
'Py' + 'thon' 'Python'
Subtraction - 35 - 22 13
Multiplication * 3 * 2 6
'Py' * 2 'PyPy'
Division / 3.0 / 2 1.5
3 / 2 1
Exponentiation ** 2 ** 0.5 1.4142135623730951
Remainder % 13 % 5 3