Python Basic Syntax

The Python language has many similarities to other languages such as Perl, C, and Java. However, there are some specific variations among these languages.

First Python Program

Execution of  programs in various modes of programming are as follows:

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.
>>>

Type the given text at the Python prompt then press the Enter −

>>> print "Hello, Python!"

If you are running latest version of Python, then its neccessary to use print statement with parenthesis as in print ("Hello, Python!");. However in Python version 2.4.3, this generates the result as follows −

Hello, Python!

Script Mode Programming:

Invoking the interpreter with a script parameter starts the execution of the script and go on until the script is finished. When the script is accomplished, the interpreter is no longer active.

Let us write a  basic Python program in a script. Extension of Python files is  .py. Type the source code in a test.py file same as follows:

print "Hello, Python!"

We estimate that you have Python interpreter set in PATH variable. Now, try to run this program given as follows −

$ python test.py

This generates the following result −

Hello, Python!

Now, try alternative way to execute a Python script. Here is the customized test.py file −

#!/usr/bin/python

print "Hello, Python!"

We think that you have Python interpreter available in /usr/bin directory. Now, try to run this program given as follows −

$ chmod +x test.py     # This is to make file executable
$./test.py

This generates the following result −

Hello, Python!

Python Identifiers

A Python identifier is a term that helps to identify a variable, function, class, module or some other object. An identifier begins with a letter A to Z (uppercase) or a to z (lowercase) or an underscore (_)  which is followed by zero or some other letters, underscores and digits (0 to 9).

Python does not permit punctuation characters for instance @, $, and % etc within identifiers. Python is case sensitive programming language. Due to this, Manpower and manpower are two distinct identifiers in Python.

Lets discuss some naming conventions for Python identifiers −

  • Class names always begin with an uppercase letter, while all other identifiers begin with a lowercase letter.

  • The identifier is private when it starts with single leading underscore but if it begins with two leading underscores then it expresses the strongly private identifier.

  • If the identifier also ends with two trailing underscores then the identifier is a language-defined special term.

Reserved Words

The list which is given below explains the Python keywords. These are reserved words which cannot be used as constant, variable or any other identifier names. All the Python keywords consists only lowercase letters.

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

Lines and Indentation

Python does not provide any braces to express blocks of code for class and function definitions or flow control. So, line indentation denote the blocks of code.

The total number of spaces in the indentation is variable, but all statements within the block must be indented the same quantity. For instance −

if True:
   print "True"
else:
   print "False"

However, the following block produces an error −

if True:
print "Answer"
print "True"
else:
print "Answer"
print "False"

Thus, in Python all the endless lines indented with equal  number of spaces would design a block. The following example has numerous statement blocks −

Note − At this point of time, make sure you understood different blocks even if they are without braces rather than understanding the logic.

#!/usr/bin/python

import sys

try:
   # open file stream
   file = open(file_name, "w")
except IOError:
   print "There was an error writing to", file_name
   sys.exit()
print "Enter '", file_finish,
print "' When finished"
while file_text != file_finish:
   file_text = raw_input("Enter text: ")
   if file_text == file_finish:
      # close the file
      file.close
      break
   file.write(file_text)
   file.write("\n")
file.close()
file_name = raw_input("Enter filename: ")
if len(file_name) == 0:
   print "Next time please enter something"
   sys.exit()
try:
   file = open(file_name, "r")
except IOError:
   print "There was an error reading file"
   sys.exit()
file_text = file.read()
file.close()
print file_text

Multi-Line Statements

Statements in Python oftenly end with a new line.However, Python permit the use of the line continuation character (\) to indicate that the line should continue. For example −

total = item_one + \
        item_two + \
        item_three

Its not necessary to use the line continuation character in the statements that are written within  [], {}, or () brackets. For instance -

days = ['Monday', 'Tuesday', 'Wednesday',
        'Thursday', 'Friday']

Quotation in Python

Python allows only single ('), double (") and triple (''' or """) quotes to indicate string literals, untill the same type of quote begins and ends the string.

The triple quotes are used to span the string across multiple lines. For instance, 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."""

Comments in Python

A hash sign (#) which is not inside the string literal starts 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.

#!/usr/bin/python

# First comment
print "Hello, Python!" # second comment

This produces the following result −

Hello, Python!

Its possible to 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.
# This is a comment, too.
# This is a comment, too.
# I said that already.

Python interpreter also ignored the following triple-quoted string and can be used as a multiline comments:

'''
This is a multiline
comment.
'''

Using Blank Lines

A line consisting only whitespace, with a comment, is known as a blank line which is totally ignored by Python.

In an interactive interpreter session, its important to enter an empty physical line to end a multiline statement.

Waiting for the User

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 −

#!/usr/bin/python

raw_input("\n\nPress the enter key to exit.")

Here, "\n\n" is used to produce two new lines before displaying the actual line. Once the user presses the key, the program terminates. This is a brilliant trick to keep a console window open until the user completes with an application.

Multiple Statements on a Single Line

The semicolon ( ; ) permits  statements on the single line given that no statement begins a new code block. Lets see the 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 create a single code block are known as suites in Python. Compound or complex statements for example if, while, def, and class need a header line and a suite.

Header lines start the statement (with the keyword) and end with a colon ( : ) and are followed by one or more lines which develops the suite. For example −

if expression : 
   suite
elif expression : 
   suite 
else : 
   suite

Command Line Arguments

A number of programs can be run to provide you some basic knowledge about how they should be run. Python makes you able  to do this with -h −

$ python -h
usage: python [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-c cmd : program passed in as string (terminates option list)
-d     : debug output from parser (also PYTHONDEBUG=x)
-E     : ignore environment variables (such as PYTHONPATH)
-h     : print this help message and exit

[ etc. ]