1. Technology
You can opt-out at any time. Please refer to our privacy policy for contact information.

Discuss in my forum

Linux Newbie Administrator Guide


8.2.2 Python


Modern and very elegant object oriented interpreter. Powerful and (arguably) more legible than perl. Very good (and large) free handbooks by G. van Rossum (the Python creator) are available on the net (try: http://www.python.org/doc/ for browsing or ftp://ftp.python.org for downloading).

How do I write a simple Python program?

Edit a text file that will contain your Python program. I can use the kde "kate" editor to do it (under X):

kate try_python.py &

Type in some simple python code to see if it works:

#!/usr/bin/env python

print 2+2

The first line (starting with the "pound-bang") tells the shell how to execute this text file--it must be there (always as the first line) for Linux to know that this particular text file is a Python script. The second line is a simple Python expression.

After saving the file, I make it executable:

chmod a+x try_python.py

after which I can run it by typing:


Python is an excellent, and very modern programming language. Give it a try, particularly if you like object oriented programming. There are numerous libaries/extensions available on the Internet. For example, scientific python (http://starship.python.net/crew/hinsen/scientific.html) and numeric python (http://sourceforge.net/projects/numpy) are popular libraries used in engineering.

Here is a slightly longer, but still (hopefully) self-explanatory python code. A quick note: python flow control depends on the code indentation--it makes it very natural looking and forcing legibility, but takes an hour to get used to.

#!/usr/bin/env python

# All comments start with a the character "#"

# This program converts human years to dog years

# get the original age

age = input("Enter your age (in human years): ")

print # print a blank line

# check if the age is valid using a simple if statement

if age < 0:

print "A negative age is not possible."

elif age < 3 or age > 110:

print "Frankly, I don't believe you."


print "That's the same as a", age/7, "year old dog."

* License

* Linux Newbie Administrator Guide Index

  1. About.com
  2. Technology
  3. Linux

©2014 About.com. All rights reserved.