Python Basic Syntax

0
157

Python is a very versatile language and has multiple advantages that make it suitable for numerous applications. It has many similarities with Perl, Java, and C. All major companies like NASA, Facebook, Google etc. have started incorporating Python based codes to support their web pages, technical applications, and search engines. Python is a very dynamic language with object-oriented features and libraries that support multiple applications as per the requirement. Since it is an open source language, installing and using it for various tasks or jobs is easy and simple. Below tutorial will take you through some basic syntax in the Python language.

Also Read: Python Environment Setup

 First Python Program

Programs in Python can be executed in different programming modes:

Interactive Mode Programming

If the interpreter is invoked without using a script file as a parameter then the following prompt comes up:

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

>>> 

Python commands can be written at the prompt and executed by hitting Enter –

>>> print “Hello, Python!”

The output of this command would be – Hello, Python!

In the newer version of Python the command would change to – print (“Hello, Python!”), parenthesis has to be included for executing the print command.

Script Mode Programming

If the interpreter is invoked with a script parameter then the script is executed till it reaches the end of the file. Post-execution of the script the interpreter becomes inactive. Let us take a simple example. Python files should have the extension .py. Let’s type the bellow source code in the test.py file –

print “Hello, Python!”

Assuming that the PATH variable is set for the Python Interpreter we can run the program as follows:

$ python test.py

This output of this execution would be:

Hello, Python!

Another way to run a Python script would be to make the file executable. Modify the test.py file with the source code shown below:

#!/usr/bin/python

print “Hello, Python!”

Assuming that the Python interpreter is available in the path – /usr/bin directory we can run the script as follows:

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

$./test.py

This output of this execution would be:

Hello, Python!

Python Identifiers

The Python identifiers are names assigned to recognize a variable, class, function, module or other objects defined in the Python script. Generally, an identifier starts with an alphabet from A to Z or a to z. It can also start from an underscore (_) followed by a zero or other letters, digits etc. Punctuations like @, $, %, ^ etc. cannot be used while defining the identifiers. The identifiers are case sensitive as well, hence Vector and vector are considered as two different entities in Python.

Below are some rules that you need to follow for naming Python Identifiers:

1.      Identifiers defining Class should start with an Uppercase letter. Other identifiers can start with either an uppercase or lowercase alphabets.

2.      If an identifier starts with one leading underscore then it is considered as the private identifier.

3.      If an identifier starts with two leading underscores then it is considered as a strongly private identifier.

4.      If an identifier ends with two trailing underscores then it is considered a language-defined special name identifier.

Reserved Words

Python has certain keywords reserved for executing standards commands in the script. These words cannot be used to define a variable or a constant or an identifier. All the reserved keywords have lowercase letters. Make sure not to use these reserve words while writing your Python script to prevent any program failure or error. Below is the list of the reserve keywords pre-defined in Python libraries.

 

and

exec

del

class

not

assert

finally

import

from

or

except

lambda

try

print

yield

else

is

continue

def

with

elif

in

global

if

while

break

for

raise

return

pass

 

Lines and Indentation

No braces are provided in Python to indicate the blocks of code. Same is the case with function definitions and flow controls. The line indentation denotes the blocks of code and has to be followed strictly. The number of spaces can vary, but all the lines in a single block should have the same indentation. Let’s look at the code below:

if True:

   print “True”

else:

   print “False”

The above code shows the correct indentation allowed by Python. The code shown below will give an error due to the wrong indentation.

if True:

print “Answer”

print “True”

else:

print “Answer”

print “False”

Hence, in Python, if a continuous section of lines has the same number of spaces then they would be considered to be in a single block. The code below shows how indentations and blocks work in Python. Use the below code to understand the blocks defined in the code. We will understand the code logic in another tutorial.

#!/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

A new line generally means a start of a new command in Python script. But line continuation can be used by using the character ‘\’ to define that line is still continuing. An example code is below:

total = item_one + \

        item_two + \

        item_three

If some commands are within brackets like [], (), {} etc. then there is no need to use the line continuation character. See the below code for reference:

days = [‘Monday’, ‘Tuesday’, ‘Wednesday’,

        ‘Thursday’, ‘Friday’]

Quotation in Python

Single (‘), double (“) or triple (‘’ or “””) quotes can be used to define strings in Python. Make sure that you use the same type of quote in defining the string. The triple quotes help in defining strings having longer length and span across multiple lines. See the below example for reference.

word = ‘word’

sentence = “This is a sentence.”

paragraph = “””This is a paragraph. It is

made up of multiple lines and sentences.”””

Comments in Python

Adding a hash sign (#) before any lines make the Python interpreter ignore the entire line as it assumes it to be a part of a comment. This helps in adding explanatory notes in the code to help in the debug process later. For example:

#!/usr/bin/python

# First comment

print “Hello, Python!” # second comment

The above source code gives the below output:

Hello, Python!

A comment can be typed even at the end of a command line. The example is below:

name = “Madisetti” # This is again comment

Multiple comment lines can also be defined in Python as shown below:

# This is a comment.

# This is a comment, too.

# This is a comment, too.

# I said that already.

Using Blank Lines

A line that has only whitespaces or a comment is considered blank and is completely ignored by the Python interpreter. In an interactive session, an empty line is needed to end a multiline statement.

Waiting for the User

To display a prompt and take input from the user the command “raw_input” can be used. Once a user has entered the required input and hit Enter, the Python script will continue processing the program. An example is below:

#!/usr/bin/python

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

The character “\n\n”\ will create two lines before printing the text. Once the user hits Enter the program ends.

Multiple Statements on a Single Line

The character semicolon (;) gives the indication to the Python Interpreter about the end of a command. Multiple commands can be executed in a single line if they are separated by the semicolon. A sample is shown below:

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

Multiple Statement Groups as Suites

The group of statements that define a single block in the code is called suites in Python. Complex or compound statements like if, else, while, try etc. need a header line and a suite. The header lines end with a colon (:) and is followed by few lines of executable commands forming a suite. An example is below:

if expression :

   suite

elif expression :

   suite

else :

   suite

Command Line Arguments

Some basic commands that Python enables to understand code characteristics can be done by using ‘-h’ as shown below:

$ python -h

usage: python [option] … [-c cmd | -m mod | file | -] [arg] …

Explanation:

-c cmd: the program is passed in as a string.

-d: displays the debug output from the parser

-E: ignores the environment variables

-h: prints the help message and exits

Summary:

Python is a very robust language and easy to learn. The above tutorial will get you started with basic coding in Python and help you in understanding its syntax as well.