Python Programming for Beginners

If you want to outsmart the Spanish Inquisition, learn Python. This article is a practical introduction to writing non-trivial applications in Python.

Despite what assembly code and C coders
might tell us, high-level languages do have their place in every
programmer's toolbox, and some of them are much more than a
computer-science curiosity. Out of the many high-level languages we
can choose from today, Python seems to be the most interesting for
those who want to learn something new and do real work at the same
time. Its no-nonsense implementation of object-oriented programming
and its clean and easy-to-understand syntax make it a language that
is fun to learn and use, which is not
something we can say about most other languages.

In this tutorial, you will learn how to write applications
that use command-line options, read and write to pipes, access
environment variables, handle interrupts, read from and write to
files, create temporary files and write to system logs. In other
words, you will find recipes for writing real applications instead
of the old boring Hello, World! stuff.

Getting Started

To begin, if you have not installed the Python interpreter on
your system, now is the time. To make that step easier, install the
latest Python distribution using packages compatible with your
Linux distribution. rpm, deb and tgz are also available on your
Linux CD-ROM or on-line. If you follow standard installation
procedures, you should not have any problems.

Next, read the excellent Python Tutorial
written by Guido van Rossum, creator of the Python programming
language. This tutorial is part of the official Python
documentation, and you can find it in either the
/usr/doc/python-docs-1.5.2 or /usr/local/doc/python-docs-1.5.2
catalog. It may be delivered in the raw LaTeX format, which must be
processed first; if you don't know how to do this, go to
http://www.python.org/doc/
to download it in an alternative format.

I also recommend that you have the Python Library
Reference handy; you might want it when the explanations
given here do not meet your needs. You can find it in the same
places as the Python Tutorial.

Creating scripts can be done using your favorite text editor
as long as it saves text in plain ASCII format and does not
automatically insert line breaks when the line is longer than the
width of the editor's window.

Always begin your scripts with either

#! /usr/local/bin/python

or

#! /usr/bin/python

If the access path to the python binary on your
system is different, change that line, leaving the first two
characters (#!) intact. Be sure this line is
truly the first line in your script, not just the first non-blank
line—it will save you a lot of frustration.

Use chmod to set the file
permissions on your script to make it executable. If the script is
for you alone, type chmod 0700
scriptfilename.py; if you want
to share it with others in your group but not let them edit it, use
0750 as the chmod value; if you want to give
access to everyone else, use the value 0755. For
help with the chmod command, type man
chmod.

Reading Command-Line Options and
Arguments

Command-line options and arguments come in handy when we want
to tell our scripts how to behave or pass some arguments (file
names, directory names, user names, etc.) to them. All programs can
read these options and arguments if they want, and your Python
scripts are no different.

Implementing appropriate handlers boils down to reading the
argv list and checking for the options and
arguments you want your script to recognize. There are a few ways
to do this. Listing 1 is a simple option handler that recognizes
common -h, -help and --help options, and when they are found, it
exits immediately after displaying the help message.

Copy and save this script as help.py, make it executable with
the chmod 0755 help.py command, and
run it several times, specifying different options, both recognized
by the handler and not; e.g. with one of the options, you will see
this message: ./help.py -h or
./help.py -o. If the option handler does
recognize one of the options, you will see this message:

If you invoke help.py with an option it
does not recognize, or without any options at all, it will display
the “I don't recognize this option” message.

Note that we need to import the
sys module before we can check the
contents of the argv list and before we can call
the exit function. The
sys.exit statement is a safety
feature which prevents further program execution when one of the
help options is found inside the argv list. This
ensures that users don't do something dangerous before reading the
help messages (for which they wouldn't have a need
otherwise).

The simple help option handler described above works quite
well and you can duplicate and change it to recognize additional
options, but that is not the most efficient way to recognize
multiple options with or without arguments. The “proper” way to
do it is to use the getopt module,
which converts options and arguments into a nice list of tuples.
Listing 2 shows how it works.

Copy this script, save it as options.py and make it
executable. As you can see, it uses two modules: sys and getopt
which are imported right at the beginning. Then we define a simple
function that displays the help message whenever something goes
wrong.

The actual processing of command-line arguments begins with
the try statement, where we are testing the list
of command-line options and arguments (sys.argv) for errors defined
as unknown options or missing arguments; if they are detected, the
script will display an error message and exit immediately (see the
except statement group). When no errors have
been detected, our script splits the list of options and their
arguments into tuples in the options list and
begins parsing them by executing a series of loops, each searching
for one option and its expected arguments.

The getopt.getopt function
generates two lists in our sample script:
options which contains options and their
arguments; and xarguments which contains
arguments not related to any of the options. We can safely ignore
them in most cases.

To recognize short (one-letter such as -h)
and long (those prefixed with --) options,
getopt.getopt uses two separate arguments. The list of short
options contains all of them listed in a single string, e.g.,
getopt.getopt(sys.argv, 'ahoinmdwq'). It is
possible to specify, in that string, options that absolutely
require an argument to follow them immediately (e.g.,
-vfilename) or after
a space (e.g., -v
filename). This is done by
inserting a colon (:) after the option, like
this:
getopt.getopt(sys.argv, 'ahoiv:emwn').
However, this creates a silly problem that may cause some confusion
and unnecessarily waste your time; if the user forgets to specify
the argument for the option that requires it, the option that
follows it becomes its argument. Consider this example:

script.py -v -h

If you put v: in the short option string
argument of the getopt.getopt function, option
-h will be treated as the argument of option
-v. This is a nuisance and makes parsing of the
list of tuples option, argument much more
difficult. The solution to this problem is simple: don't use the
colon, but check the second item of the tuple that contains the
option (first item of the analyzed tuple) which requires an
argument. If it's empty, report an error, like the
-a option handler.

Long options prefixed with -- must be
listed as a separate argument to the getopt.getopt, e.g.,
getopt.getopt(sys.argv, 'ah', ['view', 'file=']).
They can be serviced by the same handler as short options.

What you do after locating options given by the user is up to
you. Listing 2 can be used as a template for your scripts.

I tried using os.environ[] as in Listing 17. It worked while I stayed withing the python script. Once I left the python script all my environment variables returned to their original values. How do I use python to change environment variables? Do I have to use a different language?

Python Programming for Beginners it's rally true. I saw some feature of this python program excellent. I hope in near future they will add more integration on the use of this program. I feel good to read this article about python program.investment in leeds.

One important educational thing I have found with Python is there is a need to jump further into it than one might when undertaking learning a new language. I feel this way, because you can learn Python as a C/C++/Java developer, and Python is so powerful, it will oblige. However, you might be writing inefficient code.

Mark Pilgrim's Dive Into Python and Dive Into Python 3 are the only books that take a full shovelful of Python and present it all to you, so you start using generators and iterators early on. My early attempts have thankfully been corrected in forums, so that I am not writing C code in Python, but start to write procedural and functional code in python.

Python always looks like a great way to start programming but when you toss in the lack of easy to use GUI elements - it becomes cumbersome or native fileSystem support (so you have to tweak with it in order to do something that a one line DOS batch script can do).

Linux really needs an all-purpose, easy to use scripting/programming language akin to some of those found on Windows systems.

Rebol might be the answer - we'll see how version 3.0 comes along. It's also suppose to be cross-platform (some high costs if you want to compile, access DBs).

Would love to see something like AutoHotkey, Autoit, RapidBatch or even a better type of HTA (just to name a few) for Linux.

No offense intended (I know this is an old post too), but people today want to be effective right away. There are multiple solutions for other platforms (Windows for sure, don't know about Mac). Why does Linux keep reinventing the same wheel that really doesn't go anywhere?

Python has excellent toolkits (Gtk, wx, Qt), visual GUI designers and IDEs, and huge libraries. It's so good that many Windows applications are written in it, and many people choose Linux because scripting is so poor on Windows. If you want something more scripting oriented, you have Tcl/Tk, Expect, Bash, and Perl. Instead of HTA, you get Firefox and xulrunner (depending on what level of control you want). All of those are copiously documented. AutoHotkey, Autoit, and RapidBatch don't even come close, and Windows is comparatively poor when it comes to scripting.

\"Linux really needs an all-purpose, easy to use scripting/programming language akin to some of those found on Windows systems.\"

Well, I don't about you, but perl, python and bash(if you may) seems to be the all-purpose, easy to use scripting/programming language for most linux users (not windows).
Not to be rude, but why compare Windows with Linux? Okay, it may be a little too apparent that your a Windows person and a Linux critic. I can tell with you using the words "easy" and "GUI" with at most prevalence.

Perhaps, Linux isn't reinventing the same wheel as you may have perceived it, but rather modifies or creates a new version of the existing wheel. So, instead of having a poorly crafted wheel made out of rock as it was stereotypically first invented, the wheel is crafted to specific needs through current technology and resources at hand. Hopefully, you understand the analogy.

I've been looking at a number of programming and scripting languages of late. Came across 'Titanium' which is a cross-platform solution for Windows, Linux, OSX as well as iPhone and Android. It's able to work with JS, Python, PHP and a host of other softTech.

This ll take input and return in the form of string.
To get the inputin int form input is enough.
Though you can convert int from string just by writing
int(string)
where String is that String which is to be converted into int.

There are lots of tutoria and plenty of "first" examples (ie hello world) but is there a location where I can find several more stepped examples in python, of increasing difficulty and scope? Or at least be pointed at some sites who's applications make good examples?

I can google "python download" or go to sourceforge; but those are mostly not written to be teaching tools and make too big a jump from "hello world" to "how to compute the answer to life, the universe and everything".

As Linux continues to play an ever increasing role in corporate data centers and institutions, ensuring the integrity and protection of these systems must be a priority. With 60% of the world's websites and an increasing share of organization's mission-critical workloads running on Linux, failing to stop malware and other advanced threats on Linux can increasingly impact an organization's reputation and bottom line.

Most companies incorporate backup procedures for critical data, which can be restored quickly if a loss occurs. However, fewer companies are prepared for catastrophic system failures, in which they lose all data, the entire operating system, applications, settings, patches and more, reducing their system(s) to “bare metal.” After all, before data can be restored to a system, there must be a system to restore it to.

In this one hour webinar, learn how to enhance your existing backup strategies for better disaster recovery preparedness using Storix System Backup Administrator (SBAdmin), a highly flexible bare-metal recovery solution for UNIX and Linux systems.