Python – Basic Syntax

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

Type the following text at the Python prompt and press the Enter:

>>> print "Hello, Python!"

If you’re using a newer version of Python, you’ll need to use the print statement enclosed in parenthesis, as in print (“Hello, Python!”);. In Python 2.4.3, however, this yields the following result:

Hello, Python!

Script Mode Programming

Invoking the interpreter with a script parameter starts the script’s execution and continues until it is completed. The interpreter is turned off when the script is done. Let’s write a script for a simple Python program. The extension.py is used for Python files. In a test.py file, type the following source code:

print "Hello, Python!"

We’ll presume you’ve set the Python interpreter in your PATH variable. Now, try running this program like this:

$ python test.py

This produces the following result:

Hello, Python!

Let us try another way to execute a Python script. Here is the modified test.py file −

#!/usr/bin/python

print "Hello, Python!"

We’ll assume you have the Python interpreter in your /usr/bin directory. Now, try running this program like this:

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

This produces the following result −

Hello, Python!

Python Identifiers

A Python identifier is a name for a variable, function, class, module, or other object in Python. An identifier begins with a letter from A to Z, or a to z, or an underscore (_), then zero or more letters, underscores, or numbers (0 to 9). Within identifiers, punctuation characters like @, $, and percent are not allowed. Python is a programming language that is case sensitive. As a result, in Python, manpower and manpower are two separate identifiers. The naming standards for Python identifiers are as follows:

  • The name of the class begins with an uppercase letter. The beginning of all other identifiers is a lowercase letter.
  • The presence of a single leading underscore in an identifier implies that it is private.
  • An identification that begins with two leading underscores is considered to be very private.
  • The identifier is a language-defined special name if it also ends with two trailing underscores.

Lines and Indentation

There are no brackets in Python to mark code blocks for class and function definitions or flow control. Line indentation, which is strictly enforced, is used to designate code blocks. The indentation can be any number of spaces, but all statements in the block must be indented the same amount. For examples,

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

However, the following block generates an error −

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

Thus, in Python, a block is formed by all continuous lines indented by the same amount of spaces. The following sample contains a number of different statement blocks. Note: Do not attempt to understand the logic at this time. Just double-check that you understand the individual blocks, even if they aren’t braced.

Multi-Line Statements

In Python, statements usually start on a new line. The line continuation character () in Python, on the other hand, can be used to indicate that the line should continue. For example,

total = item_one + \
        item_two + \
        item_three

The line continuation character is not required for statements enclosed in the [], {}, or () .For example,

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

Quotation in Python

To indicate string literals, Python accepts single (‘), double (“), and triple (“‘ or “””) quotes, as long as the same type of quote begins and ends the string. To span the string across multiple lines, triple quotes are utilized. All of the following, for example, are legal:

codelivly = 'codelivly'
sentence = "This is a sentence."
paragraph = """This is a paragraph. It is
made up of multiple lines and sentences."""

Comments in Python

A comment begins with a hash sign (#) outside of a string literal. The Python interpreter ignores any characters after the # and up to the end of the physical line as part of the comment.

#!/usr/bin/python

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

You can type a comment on the same line after a statement or expression −

name = "Codelivly" # 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.

Multiple Statements on a Single Line

Because neither statement starts a new code block, the semicolon (;) permits several statements on a single line. Here’s an example of how to use the semicolon.

import sys; x = 'foo'; sys.stdout.write(x + '\n')

Multiple Statement Groups as Suites

In Python, a suite is a collection of specific statements that form a single code block. A header line and a suite are required for compound or complex statements like if, while, def, and class. The statement (containing the keyword) is started with a header line, which ends with a colon (:), and is followed by one or more lines that make up the suite. For example,

if expression : 
   suite
elif expression : 
   suite 
else : 
   suite

Waiting for the User

The program’s next line shows the prompt and the line “Press the enter key to exit,” and then waits for the user to respond.

#!/usr/bin/python

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

Leave a Comment

Your email address will not be published.