Interactive Mode

Python has an interactive mode. You can type Python code and see the results immediately. To start Python, open a unix shell and type "python".

> python
Python 2.3.3 (#1, Jan 29 2004, 22:55:13) 
[GCC 3.3.3 [FreeBSD] 20031106] on freebsd5
Type "help", "copyright", "credits" or "license" for more information.
>>>
At the >>> prompt you can enter Python code.

Using Python as a calculator


>>> 2+3
5
>>> 4+6*8
52
>>> abs(-4)
4
>>> help(abs)
Help on built-in function abs:

abs(...)
    abs(number) -> number
    
    Return the absolute value of the argument.

>>> 89**34
1902217732808760980190430983601716818363305103120555045416541165041L
>>> print 89**34
1902217732808760980190430983601716818363305103120555045416541165041
>>> "What... is the air-speed velocity of an unladen swallow?"
'What... is the air-speed velocity of an unladen swallow?'
>>> print "What do you mean?  An African or European swallow?"
What do you mean?  An African or European swallow?
>>> 

Importing a module

Python organizes functions into modules. There are a lot of built-in modules and even more "third-party" modules (also called packages).

>>> import math
>>> help(math)
Help on module math:

NAME
    math

FILE
    /usr/local/lib/python2.3/lib-dynload/math.so

DESCRIPTION
    This module is always available.  It provides access to the
    mathematical functions defined by the C standard.

FUNCTIONS
    acos(...)
        acos(x)
        
        Return the arc cosine (measured in radians) of x.
    
    asin(...)
        asin(x)
        
        Return the arc sine (measured in radians) of x.
    
 [... rest of the output removed ...]
>>> math.pi
3.1415926535897931
>>> math.sin(math.pi/2.0)
1.0
>>> 

Print the Time of Day


>>> import datetime
>>> now = datetime.datetime.now()
>>> now
datetime.datetime(2004, 2, 2, 19, 23, 28, 809434)
>>> print now
2004-02-02 19:23:28.809434
>>> print "Now is", now.strftime("%d-%m-%Y"), "at", now.strftime("%H:%M")
Now is 02-02-2004 at 19:23
>>> 
The notation name1.name2 is called an attribute lookup. In this case, name2 is an attribute of name1 and has some value.

>>> now.day
2
>>> now.year
2004
>>> now.hour
19
>>> 

This page based on Some Simple Scripts.


Andrew Dalke
Last modified: Tue Feb 3 11:37:43 SAST 2004