Friday, June 20, 2008

The Basics

Printing Predefinded string like "Hello World" is not enough, is it? In programming we need more than that - we want to take some input, manipulate it and get something with some logic out of it. we achieve such in almost all programming laguage using constants and variables.

Literal Constants
Literal constant is anything such as 5, 1.23, 9.25e-3 or a string like "This is a literal." or 'This is a literal'. This is caled literal because we use its valuse literally. The literal present their own value nothing else; 2 is just 2 : ).

Numbers
Numbers in Python are of four types - integers, long integers, floating point and complex numbers.
  • Examples of integers are 2 which are just whole numbers.
  • Long integers are just bigger whole numbers.
  • Examples of floating point numbers (or floats for short) are 3.23 and 52.3E-4. The E notation indicates powers of 10. In this case, 52.3E-4 means 52.3 * 10-4.
  • Examples of complex numbers are (-5+4j) and (2.3 - 4.6j)
Strings
A string is a sequence of characters. Strings are basically just a bunch of words.
I can almost guarantee that you will be using strings in almost every Python program that you write, so pay attention to the following part. Here's how you use strings in Python:
  • Using Single Quotes (')
You can specify strings using single quotes such as 'Quote me on this' . All white space i.e.spaces and tabs are preserved as-is.
  • Using Double Quotes (")
Strings in double quotes work exactly the same way as strings in single quotes. An example is "What's your name?"
  • Using Triple Quotes (''' or """)
You can specify multi-line strings using triple quotes. You can use single quotes and double quotes freely within the triple quotes. An example is:
'''This is a multi-line string. This is the first line.
This is the second line.
"What's your name?," I asked.
He said "Bond, James Bond."
'''
  • Escape Sequences
Suppose, you want to have a string which contains a single quote ('), how will you specify this string? For example, the string is What's your name?.

You cannot specify 'What's your name?' because Python will be confused as to where the string starts and ends. So, you will have to specify that this single quote does not indicate the end of the string. This can be done with the help of what is called an escape sequence. You specify the single quote as \' - notice the backslash. Now, you can specify the string as 'What\'s your name?'.

Another way of specifying this specific string would be "What's your name?" i.e. using double quotes. Similarly, you have to use an escape sequence forusing a double quote itself in a double quoted string. Also, you have to indicate the backslash itself using the escape sequence \\.

What if you wanted to specify a two-line string? One way is to use a triple-quoted string as shown above or you can use an escape sequence for the newline character - \n to indicate the start of a new line. An example is This is the first line\nThis is the second line . Another useful escape sequence to know is the tab - \t. There are many more escape sequences but I have mentioned only the most useful ones here.

One thing to note is that in a string, a single backslash at the end of the line indicates that the string is continued in the next line, but no newline is added.

For example,

"This is the first sentence.\
This is the second sentence."

is equivalent to "This is the first sentence. This is the second sentence."
  • Raw Strings
If you need to specify some strings where no special processing such as escape sequences are handled, then what you need is to specify a raw string by prefixing r or R to the string. An example is r"Newlines are indicated by \n".
  • Unicode Strings
Unicode is a standard way of writing international text. If you want to write text in your native language such as Punjabi, Hindi or Arabic, then you need to have a Unicode-enabled text editor. Similarly, Python allows you to handle Unicode text - all you need to do is prefix u or U. For example, u"This is a Unicode string.".
Remember to use Unicode strings when you are dealing with text files, especially when you know that the file will contain text written in languages other than English.
  • Strings are immutable
This means that once you have created a string, you cannot change it. Although this might seem like a bad thing, it really isn't. We will see why this is not a limitation in the various programs that we see later on.
  • String literal concatenation
If you place two string literals side by side, they are automatically concatenated by Python. For example, 'What\'s' 'your name?' is automatically converted in to "What's your name?".
Note for C/C++ Programmers
There is no separate char data type in Python. There is no real need for it and I am sure you won't miss it.

Note for Perl/PHP Programmers
Remember that single-quoted strings and double-quoted strings are the same - they do not differ in any way.

Note for Regular Expression Users
Always use raw strings when dealing with regular expressions. Otherwise, a lot of backwhacking may be required. For example, backreferences can be referred to as '\\1' or r'\1'.
Variables
Using just literal constants can soon become boring - we need some way of storing any information and manipulate them as well. This is where variables come into the picture. Variables are exactly what they mean - their value can vary i.e. you can store anything using a variable. Variables are just parts of your computer's memory where you store some information. Unlike literal constants, you need some method of accessing these variables and hence you give them names.

Identifier Naming
Variables are examples of identifiers. Identifiers are names given to identify something. There are some rules you have to follow for naming identifiers:
  • The first character of the identifier must be a letter of the alphabet (upper or lowercase) or an underscore ('_').
  • The rest of the identifier name can consist of letters (upper or lowercase), underscores ('_') or digits (0-9).
  • Identifier names are case-sensitive. For example, myname and myName are not the same. Note the lowercase n in the former and the uppercase N in the latter.
  • Examples of valid identifier names are i, __my_name, name_23 and a1b2_c3.
  • Examples of invalid identifier names are 2things, this is spaced out and my-name.
Data Types
Variables can hold values of different types called data types. The basic types are numbers and strings, which we have already discussed. In later chapters, we will see how to create our own types using classes.

Objects
Remember, Python refers to anything used in a program as an object. This is meant in the generic sense. Instead of saying 'the something', we say 'the object'.

Note for Object Oriented Programming users
Python is strongly object-oriented in the sense that everything is an object including numbers, strings and even functions.
We will now see how to use variables along with literal constants. Save the following example and run the program.

How to write Python programs
Henceforth, the standard procedure to save and run a Python program is as follows:
1. Open your favorite editor.
2. Enter the program code given in the example.
3. Save it as a file with the filename mentioned in the comment. I follow the convention of having all Python programs saved with the extension .py.
4. Run the interpreter with the command python program.py or use IDLE to run the programs. You can also use the executable method as explained earlier.
Example. Using Variables and Literal constants

# Filename : var.py
i = 5
print i
i = i + 1
print i
s = '''This is a multi-line string.
This is the second line.'''
print s

Output:
$ python var.py
5
6
This is a multi-line string.
This is the second line.


How It Works
Here's how this program works. First, we assign the literal constant value 5 to the variable i using the assignment operator (=). This line is called a statement because it states that something should be done and in this case, we connect the variable name i to the value 5. Next, we print the value of i using the print statement which, unsurprisingly, just prints the value of the variable to the screen.
Then we add 1 to the value stored in i and store it back. We then print it and expectedly, we get the value 6.
Similarly, we assign the literal string to the variable s and then print it.

Note for C/C++ Programmers
Variables are used by just assigning them a value. No declaration or data type definition is needed/used.
Logical and Physical Lines
A physical line is what you see when you write the program. A logical line is what Python sees as a single statement. Python implicitly assumes that each physical line corresponds to a logical line.
An example of a logical line is a statement like print 'Hello World' - if this was on a line by itself (as you see it in an editor), then this also corresponds to a physical line.
Implicitly, Python encourages the use of a single statement per line which makes code more readable.
If you want to specify more than one logical line on a single physical line, then you have to explicitly specify this using a semicolon (;) which indicates the end of a logical line/statement. For example,

i = 5
print i

is effectively same as

i = 5;
print i;

and the same can be written as

i = 5; print i;

or even

i = 5; print i

However, I strongly recommend that you stick to writing a single logical line in a single physical line only. Use more than one physical line for a single logical line only if the logical line is really long. The idea is to avoid the semicolon as far as possible since it leads to more readable code. In fact, I have never used or even seen a semicolon in a Python program.

An example of writing a logical line spanning many physical lines follows. This is referred to as explicit line joining.

s = 'This is a string. \
This continues the string.'
print s

This gives the output:

This is a string. This continues the string.
Similarly,

print \
i

is the same as

print i

Sometimes, there is an implicit assumption where you don't need to use a backslash. This is the case where the logical line uses parentheses, square brackets or curly braces. This is is called implicit line joining. You can see this in action when we write programs using lists in later chapters.

Indentation
Whitespace is important in Python. Actually, whitespace at the beginning of the line is important. This is called indentation. Leading whitespace (spaces and tabs) at the beginning of the logical line is used to determine the indentation level of the logical line, which in turn is used to determine the grouping of statements.

This means that statements which go together must have the same indentation. Each such set of statements is called a block. We will see examples of how blocks are important in later chapters.

One thing you should remember is how wrong indentation can give rise to errors. For example:

i = 5
. print 'Value is', i # Error! Notice a single space at the start of the line
.print 'I repeat, the value is', i

When you run this, you get the following error:

File "whitespace.py", line 4
print 'Value is', i # Error! Notice a single space at the start of the line
^
SyntaxError: invalid syntax

Notice that there is a single space at the beginning of the second line. The error indicated by Python tells us that the syntax of the program is invalid i.e. the program was not properly written. What this means to you is that you cannot arbitrarily start new blocks of statements (except for the main block which you have been using all along, of course). Cases where you can use new blocks will be detailed in later chapters such as the control flow chapter.

How to indent
Do not use a mixture of tabs and spaces for the indentation as it does not work across different platforms properly. I strongly recommend that you use a single tab or two or four spaces for each indentation level.
Choose any of these three indentation styles. More importantly, choose one and use it consistently i.e. use that indentation style only.
Summary
Now that we have gone through many nitty-gritty details, we can move on to more interesting stuff such as control flow statements. Be sure to become comfortable with what you have read in this chapter.

First Steps

The First usual step as we did in almost all the Programming languages is "Hello World!". This will teach you how to write, save and run Python programs. There are two ways of using Python to run your program - using the interactive interpreter prompt or using a source file. We will now see how to use both the methods one by one.

Firefox 3

Using the interpreter prompt

Start the interpreter on the command line by entering python at the shell prompt. Now enter print 'Hello World' followed by the Enter key. You should

see the words Hello World as output. You can run the interpreter by IDLE program. IDLE is short for Integrated DeveLopment Environment. Click on Start -> All Programs -> Python 2.5 -> IDLE (Python GUI).

Note that the >>> signs are the prompt for entering Python statements.

EXAMPLE: Using the Python Interpreter prompt

2.5.2 (r252:60911, Feb 21 2008, 13:11:45) [MSC v.1310 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.

****************************************************************
Personal firewall software may warn about the connection IDLE
makes to its subprocess using this computer's internal loopback
interface. This connection is not visible on any external
interface and no data is sent to or received from the Internet.
****************************************************************

IDLE 1.2.2
>>> print 'Hello World'
Hello World
>>>


Notice that Python gives you the output of the line immediately! What you just entered is a single Python statement. We use print to (unsurprisingly) print any value that you supply to it. Here, we are supplying the text Hello World and this is promptly printed to the screen.

Choosing an Editor

Before we move on to writing Python programs in source files, we need an editor to write the source files. The choice of an editor is crucial indeed. You have to choose an editor as you would choose a car you would buy. A good editor will help you write Python programs easily, making your journey more comfortable and helps you reach your destination (achieve your goal) in a much faster and safer way.
One of the very basic requirements is syntax highlighting where all the different parts of your Python program are colorized so that you can see your program and visualize its running.
If you are using Windows, then I suggest that you use IDLE. IDLE does syntax highlighting and a lot more such as allowing you to run your programs within IDLE among other things. A special note: don't use Notepad - it is a bad choice because it does not do syntax highlighting and also importantly it does not support indentation of the text which is very important in our case as we will see later. Good editors such as IDLE (and also VIM) will automatically help you do this.
If you still want to explore other choices of an editor, see the comprehensive list of Python editors [http://www.python.org/cgi-bin/moinmoin/PythonEditors] and make your choice. You can also choose an IDE (Integrated Development Environment) for Python. See the comprehensive list of IDEs that support Python [http://www.python.org/cgi-bin/moinmoin/IntegratedDevelopmentEnvironments] for more details. Once you start writing large Python programs, IDEs can be very useful indeed.
I repeat once again, please choose a proper editor - it can make writing Python programs more fun and easy.

Using a Source File

Now let's get back to programming. There is a tradition that whenever you learn a new programming language, the first program that you write and run is the 'Hello World' program - all it does is just say 'Hello World' when you run it.
Start your choice of editor, enter the following program and save it as helloworld.py

Example: Using a Source File

# Filename : helloworld.py
print 'Hello World'


First Check Module by menu Run -> Check Module or keyboard Shortcut Alt+X, Then Run this program by menu Run -> Run Module Script or the keyboard shortcut F5. The output will be same as previous.
If you got the output as shown above, congratulations! - you have successfully run your first Python program.

In case you got an error, please type the above program exactly as shown and above and run the program again. Note that Python is case-sensitive i.e. print is not the same as Print - note the lowercase p in the former and the uppercase P in the latter. Also, ensure there are no spaces or tabs before the first character in each line - we will see why this is important later.

How It Works

Let us consider the first line of the program. This is called comment - anything to the right of the # symbol is a comment and is mainly useful as notes for the reader of the program.
Python does not use comments except for the special case of the first line here. Note that you can always run the program on any platform by specifying the interpreter directly on the command line such as the command python helloworld.py .
Important
Use comments sensibly in your program to explain some important details of your program - this is useful for readers of your program so that they can easily understand what the program is doing. Remember, that person can be yourself after six months!
The comments are followed by a Python statement - this just prints the text 'Hello World'. The print is actually an operator and 'Hello World' is referred to as a string - don't worry, we will explore these terminologies in detail later.

Summary
You should now be able to write, save and run Python programs at ease. Now that you are a Python user, let's learn some more Python concepts.

Thursday, June 19, 2008

Features of Python

Here in this Post I am giving Features of Python that help us to understand why Python is mentioned in big languages lik C/C++, Java or PERL.

FEATURES OF PYTHON:-
  1. Free and Open Source - Just like C++ Python is free and Open Source. It means you need not to pay to get its interpreted fully functional. And read it's source code, make changes to it, use pieces of it in new free programs, and that you know you can do these things. This is one of the reasons why Python is so good - it has been created and is constantly improved by a community who just want to see a better Python.
  2. Simple and Easy to Learn - Reading a good Python program feels almost like reading English, although very strict English! This pseudo-code nature of Python is one of its greatest strengths. It allows you to concentrate on the solution to the problem rather than the language itself. As you will see, Python is extremely easy to get started with. Python has an extraordinarily simple syntax, as already mentioned.
  3. High Level Language - When you write program in Python you need not to bother about Low level details such as memory management used by Python program.
  4. Portable - Due to its Open Source nature, Python has been ported to many platforms. All your Python programs can work on any of these platforms without requiring any changes at all if you are careful enough to avoid any system-dependent features.
    You can use Python on Linux, Windows, FreeBSD, Macintosh, Solaris, OS/2, Amiga, AROS, AS/400, BeOS, OS/390, z/OS, Palm OS, QNX, VMS, Psion, Acorn RISC OS, VxWorks, PlayStation, Sharp Zaurus, Windows CE and even PocketPC !
  5. Interpreted - This requires bit explanation if you are not a expert like stuff...
    A software written in compiled language like C/C++, After compilation code converted to the source code the language you can say spoken by computer. When you run run program Linker/Loader copy Source code from hard disk to main memory and start running it.
    On other hand, Pythonh need not to compile to binary. You just run the program from your Source Code. Internally Python convert the Source Code to intermediate forn called Bytecode the translate it into native language of your computer and then run it; all at lightning speed. This make Python easier since you need not to worry about compiling the program, make sure proper libraries are linked and loaded, etc, etc, etc.This also make you Python program more portable.
  6. Object Oriented - Here with Python you got both options to code your program Object Oriented and Subject Oriented or Procedure Oriented. Subject Oriented or Procedure Oriented programs are made around procedure or function that are nothing but reusable bunch of code. But in Object Oriented language, the program is built around objects which combine data and functionality. Python has a very powerful but simplistic way of doing OOP, especially when compaired to big languages like C++ or Java.
  7. Embeddable - We can embed Python within your C/C++ programs to give 'scripting' capabilities for you program's users.
  8. Extensive Libraries - The Python Standard Library is huge indeed. It can help you do various operations involving regular expressions, documentation generation, unit testing, threading, databases, web browsers, CGI, FTP, email, XML, HTML, WAV Files, Cryptography, GUI, tk, and other system dependent stuff.all this available wherever Python is installed. This is called "Batteries Include" philosophy of Python.
    Besides, the Standard libraries, there are various other high-quality library such as wxPython [http://www.wxpython.org], Twisted [http://www.twistedmatrix.com/products/twisted], Python Imaging library [http://www.pythonware.com/products/pil/index.htm] and many more.
So, Python is indeed an exciting and powerful language. It has the right combination of performance and features that make writing programs in Python both fun and easy.

Why I Start Python

I like C++ most but now I am planning to shift from C++ to python because in C++ for basic operation Turbo Compiler Work. Fine but in case of Graphics and Network programming it become bit hard to run program. If you are using UNIX or Linux then it is OK but in case of Window for developing such bigger applications we need to use Microsoft Visual C++ which is very heavy for PC. But in with Python compiler everything is possible at single place. Second reason is to be out of crowd I want my separate Identity… All my friends used to work on .Net, Java, C++ or PHP. Nobody think about Python.

I don’t know whether this is a proper reason to change my working language. But I am after Python now in this blog I will try to present tutorial of python in steps. What I able to get I will try to explain in easy way.

I am following not single book for Python I read all available books and online stuff for Python.

Tomorrow I will post Features of python and will try to keep this process going.