computer basics
online shopping


programming language
environment setup
data type
condition & iteration
date & time


Advanced Topics
file formats
db connections
-other db
exception handling



first python program

Interactive Mode Programming
Invoking the interpreter without passing a script file as a parameter brings up the following prompt −
$ python
Python 2.4.3 (#1, Nov 11 2010, 13:34:43)
[GCC 4.1.2 20080704 (Red Hat 4.1.2-48)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> print ("Hello, Python!")
Hello, Python!


Script Mode Programming
Invoking the interpreter with a script parameter begins execution of the script and continues until the script is finished. When the script is finished, the interpreter is no longer active.
Let us write a simple Python program in a script. Python files have extension .py. Type the following source code in a file:

print "Hello, Python!" 
$ python 
This produces the following result:
Hello, Python!
Let us try another way to execute a Python script. Here is the modified file −
print "Hello, Python!"
We assume that you have Python interpreter available in /usr/bin directory. Now, try to run this program as follows −
$ chmod +x # This is to make file executable
This produces the following result −
Hello, Python!



Python Identifiers

A Python identifier is a name used to identify a variable, function, class, module or other object. An identifier starts with a letter A to Z or a to z or an underscore (_) followed by zero or more letters, underscores and digits (0 to 9).
Python does not allow punctuation characters such as @, $, and % within identifiers. Python is a case sensitive programming language. Thus, Manpower and manpower are two different identifiers in Python.
Here are naming conventions for Python identifiers −
Class names start with an uppercase letter. All other identifiers start with a lowercase letter.
Starting an identifier with a single leading underscore indicates that the identifier is private.
Starting an identifier with two leading underscores indicates a strongly private identifier.
If the identifier also ends with two trailing underscores, the identifier is a language-defined special name.



Reserved Words

The following list shows the Python keywords. These are reserved words and you cannot use them as constant or variable or any other identifier names. All the Python keywords contain lowercase letters only.
and exec not
assert finally or
break for pass
class from print
continue global raise
def if return
del import try
elif in while
else is with
except lambda yield




Python provides no braces to indicate blocks of code for class and function definitions or flow control. Blocks of code are denoted by line indentation, which is rigidly enforced.
The number of spaces in the indentation is variable, but all statements within the block must be indented the same amount. For example −
if True:
print "True"
print "False"
However, the following block generates an error − 
if True:
print "Answer"
print "True"
print "Answer"
print "False"



Multi-Line Statements

Statements in Python typically end with a new line. Python does, however, allow the use of the line continuation character (\) to denote that the line should continue. For example −
total = item_one + \
item_two + \
Statements contained within the [], {}, or () brackets do not need to use the line continuation character. For example −
days = ['Monday', 'Tuesday', 'Wednesday',
'Thursday', 'Friday']




Python accepts single ('), double (") and triple (''' or """) quotes to denote string literals, as long as the same type of quote starts and ends the string.
The triple quotes are used to span the string across multiple lines. For example, all the following are legal −
word = 'word'
sentence = "This is a sentence."
paragraph = """This is a paragraph. It is
made up of multiple lines and sentences."""




A hash sign (#) that is not inside a string literal begins a comment. All characters after the # and up to the end of the physical line are part of the comment and the Python interpreter ignores them.
# First comment
print "Hello, Python!" # second comment
This produces the following result −
Hello, Python!
You can type a comment on the same line after a statement or expression −
name = "Madisetti" # This is again comment
You can comment multiple lines as follows −
# This is a comment.S
# This is a comment, too.



User Input

The following line of the program displays the prompt, the statement saying “Press the enter key to exit”, and waits for the user to take action −
raw_input("\n\nPress the enter key to exit.")
Here, "\n\n" is used to create two new lines before displaying the actual line. Once the user presses the key, the program ends. This is a nice trick to keep a console window open until the user is done with an application.



Multiple Statements

Multiple Statements on a Single Line
semicolon ( ; ) allows multiple statements on the single line given that neither statement starts a new code block. Here is a sample snip using the semicolon −
import sys; x = 'foo'; sys.stdout.write(x + '\n')


Multiple Statement Groups as Suites
A group of individual statements, which make a single code block are called suites in Python. Compound or complex statements, such as if, while, def, and class require a header line and a suite.
Header lines begin the statement (with the keyword) and terminate with a colon ( : ) and are followed by one or more lines which make up the suite. For example −
if expression :
elif expression :
else :




But, as we said at the beginning, we want to write a "serious" script now. We use a slight variation of the "Hello World" theme. We have to include our print statement into a file. To save and edit our program in a file we need an editor. There are lots of editors, but you should choose one, which supports syntax highlighting and indentation. Under Linux you can use vi, vim, emacs, geany, gedit and umpteen others. The emacs works under windows as well, but notepad++ may be the better choice in many cases. 
So, after you have found the editor of your choice, you can input your mini script, i.e.
print("My first simple Python script!")
and save it as 
Let's assume our script is in a subdirectory under the home directory of user monty:
monty@python:~$ cd python
monty@python:~/python$ python
My first simple Python script!
Most probably you will have read somewhere that the Python language is an interpreted programming or a script language. The truth is: Python is both an interpreted and a compiled language. But calling Python a compiled language would be misleading. (At the end of this chapter, you will find the definitions for Compilers and Interpreters, if you are not familiar with the concepts!) People would assume that the compiler translates the Python code into machine language. Python code is translated into intermediate code, which has to be executed by a virtual machine, known as the PVM, the Python virtual machine. This is a similar approach to the one taken by Java. There is even a way of translating Python programs into Java byte code for the Java Virtual Machine (JVM). This can be achieved with Jython. 
The question is, do I have to compile my Python scripts to make them faster or how can I compile them? The answer is easy: Normally, you don't need to do anything and you shouldn't bother, because "Python" is doing the thinking for you, i.e. it takes the necessary steps automatically. 
For whatever reason you want to compile a python program manually? No problem. It can be done with the module py_compile, either using the interpreter shell
>>> import py_compile
>>> py_compile.compile('')
or using the following command at the shell prompt
python -m py_compile
Either way, you may notice two things: First, there will be a new subdirectory "__pycache__", if it hasn't already existed. You will find a file "my_first_simple_script.cpython-34.pyc" in this subdirectory. This is the compiled version of our file in byte code. 
You can also automatically compile all Python files using the compileall module. You can do it from the shell prompt by running and providing the path of the directory containing the Python files to compile:
monty@python:~/python$ python -m compileall .
Listing . ...

But as we have said, you don't have to and shouldn't bother about compiling Python code. The compilation is hidden from the user for a good reason. Some newbies to Python wonder sometimes where these ominous files with the .pyc suffix might come from. If Python has write-access for the directory where the Python program resides, it will store the compiled byte code in a file that ends with a .pyc suffix. If Python has no write access, the program will work anyway. The byte code will be produced but discarded when the program exits.

Whenever a Python program is called, Python will check, if there exists a compiled version with the .pyc suffix. This file has to be newer than the file with the .py suffix. If such a file exists, Python will load the byte code, which will speed up the start up time of the script. If there exists no byte code version, Python will create the byte code before it starts the execution of the program. Execution of a Python program means execution of the byte code on the Python Virtual Machine (PVM). 
Every time a Python script is executed, byte code is created. If a Python script is imported as a module, the byte code will be stored in the corresponding .pyc file. 
So the following will not create a byte code file:
monty@python:~/python$ python
My first simple Python script!
The import in the following Python2 session will create a byte code file with the name "my_first_simple_script.pyc":
monty@python:~/tmp$ ls
monty@python:~/tmp$ python
Python 2.6.5 (r265:79063, Apr 16 2010, 13:57:41)
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import my_first_simple_script
My first simple Python script!
>>> exit()
monty@python:~/tmp$ ls my_first_simple_script.pyc