1B-Introduction To Python
1B-Introduction To Python
http://www.flos-freeware.ch/notepad2.html
http://www.python.org/download/releases/2.6.6/
http://www.barebones.com/products/TextWrangler/download.html
Why Python?
• Python is • C is much faster but
– easy to learn much harder to learn
– fast enough and use.
– object-oriented • Java is somewhat
– widely used faster but harder to
– fairly portable learn and use.
• Perl is a little slower
and a little harder to
learn.
Getting started on the Mac
• Start a terminal session
• Type “python”
• This should start the Python interpreter
(often called “IDLE”)
• Print "Hello, world!" as below if your line starts
with '>>>' you are in
> python the interpreter
Python 2.6.4 (something something)
details something something
Type "help", "copyright", "credits" or "license"
for more information.
>>> print "Hello, world!"
Hello, world!
The interpreter
• Try printing various things (in your spare time)
– Leave off the quotation marks.
– Print numbers, letters and combinations.
– Print two things, with a comma between them.
– Enter a mathematical formula.
– Leave off the word “print”.
• Each type of object has its own properties, which we will learn about in
the next few weeks.
• It is also possible to define your own type of object, comprised of
combinations of the six base types.
>>> pi = 3.14159
>>> print pi
3.14159
>>> pi = -7.2
>>> print pi you can see where
-7.2 "variable" comes from:
pi can be changed
The import command
Many python functions are available only via packages that must be
imported (other functions are always available - called built-in).
For example, the log function is in the math package:
python my-program.py 17
zeroth first
argument argument
Reading command line arguments
Access in your program like this:
import sys zeroth
print sys.argv[0] argument
print sys.argv[1] first
argument
> python my-program.py 17
my-program.py
17
import sys
print sys.argv[1], ":", sys.argv[2]
Sample problem #2
• Write a program called “add-two-args.py”
that reads the first two command line
arguments after the program name, stores
their values as number variables, and then
prints their sum.
> python add-two-args.py 1 2
3.0
Hint - to read an argument as a decimal number, use the syntax:
foo = float(sys.argv[1]) The technical name for this is "casting" -
or for an integer number: the argument starts as a string object
and is cast to a float or int object (two
bar = int(sys.argv[1]) kinds of Number objects in Python).
import sys
arg1 = float(sys.argv[1])
arg2 = float(sys.argv[2])
argSum = arg1 + arg2
print argSum
Challenge problems
Write a program called “circle-area.py” that reads the
first command line argument as the radius of a circle
and prints the area of the circle.
> python circle-area.py 15.7
774.371173183