Simple Programming Rules For Python - Python: Programming Language for Beginners - Learn In A Day! (2015)

Python: Programming Language for Beginners - Learn In A Day! (2015)

Chapter 3. Simple Programming Rules For Python

Now, let’s learn in detail some simple yet important programming rules of Python.

Go to the start menu->Python-> 'IDLE', or Integrated Development Environment.)

Type the following in the python prompt and press enter: (do not type ‘>>>’ because it is already present in the command-line)

Code Example 1 - Hello, World!

>>> print "Hello, World!"

O/p:- Hello, World!

Here is another example which shows how to print a string on the screen:

print ('hi, Michael')

The keyword ‘print’ is used to print a string on the screen. The output for the above example program is:

OUTPUT: hi, Michael

The above program can also be written as below

print 'hi, Michael'

The above program also gives the output: hi, Michael

1. Using parenthesis with the print statement is optional. It does not make a difference if it is used or not. The same output is obtained in both the cases. But, starting from Python 3.x versions, it is mandatory to use parenthesis with the print statement.

2. It is also not mandatory to use semicolon at the end of each statement. Usage of semicolon is optional.

Example: print 'hi, Michael';

We can use the semicolon ( ; ) to specify multiple statements on a single line.

Example: print 'hi'; print 'Michael'; print 'how are you?';

OUTPUT:

hi

Michael

how are you?

Commenting in Python

The comments in a program help in better understanding of the code.

Single line comment:

In Python, a comment begins with a hash sign (#). The characters following the # sign are considered a comment and are ignored by the Python interpreter. The characters following the # sign until the end of the line make a single line of comment.

Example:

# This is where you should comment

print 'hi, Michael'

#This line is considered a comment and is ignored by the interpreter

Consider few other examples:

# print "food is very bad"

(No output because the print statement was entered after a comment)

print "food is tasty" eat it

(An error message is displayed because we haven’t put the comment after the hash)

Multi line comments:

In Python, the hash (#) sign is used to write only single line comments. Multi line comments cannot be written using the hash sign. For example, consider the following script:

# This is

a Python Script

print 'hi, Michael'

The above script gives an error as the comment ‘This is a Python Script’ is written in two lines, but # sign can only allow a single line comment .So, for writing multi line comments in Python, we can use triple quotations- ''”” or””".

Example 1:

“This is a Python Script ''

print 'hi, Michael'

Example 2:

“This is a Python Script”

print 'hi, Michael'

Quotations in Python

For printing strings, Python allows using single quotes ('), double quotes(") or triple quotes (''' or"""). Care should be taken that the same type of quotes are used at the beginning and end of the string. For example, the string 'I like Python' can be printed using the print statement in the following ways:

print 'I like Python'

print "I like Python"

print '''I like Python'''

print"""I like Python"""

All of the four statements above give the same output. But, multiple lines can only be printed only using triple quotes. Attempting to print strings in multiple lines using single or double quotes gives errors.

Example:

print ''' I like Python. It is very simple and easy to learn'''

The above statement is legal as triple quotes have been used for printing multiple lines of string.

Let’s see what happens when the above script is changed as follows:

print 'I like Python. It is very simple and easy to learn'

The above statement gives an error as single quotes(or double quotes) cannot accommodate multiple lines of strings.

Now let’s take a look at another script:

print 'Python is object oriented'''

The above statement gives an error, as the string starts with a single quote but ends with a triple quote. As mentioned earlier, same type of quote needs to be specified at both ends of the string.

Now, what if you want to print single quote (') as a part of a string on the screen?

For example, what if you want to print a string 'Python'(including single quotes) on the screen? It can be done using the following statement:

print "'Python'" #Here the string to be printed is 'Python'

OUTPUT: 'Python'

Note: The statement after the # sign is a comment

What if you want to print only a single quote on the screen? It can be done using the following statement:

print '' ' '' #the single quote is in between two double quotes

OUTPUT:

Similarly, what if you want to print a double quote on the screen? You might think the following script will do the job:

print """ # The double quote to be printed is enclosed between two double quotes.

The above script will give an error as the interpreter considers the three double quotes """ as a triple quote, and not as an instruction to print a double quote. In cases like this, the backslash (\) character comes into play.

In general, the backslash (\) is used for encoding characters which are difficult to print using normal quotation marks. Escape sequences need to be used for printing such difficult-to-print characters (like quotes within quotes). You will understand what escape sequences are if you follow the given examples:

Let us consider you want to print a sentence which involves punctuations as follows:

"I am happy", said Michael. You might choose to use either single quotes or double quotes to print the above sentence. Let us suppose you have written the script as follows:

print "I am happy", said Michael." # Enclosing the sentence to be printed in double quotes.

The above script gives an error because, the Python interpreter gets confused as it assumes that the double quotes at beginning of the string "I am happy" are a part of the print syntax , and thinks that the string has ended. It will not understand that those double quotes are nothing but characters that needed to be printed as a part of the string. We need to let Python know that those double quotes are not a part of the print syntax.

This problem can be solved, if the double quotes around the string "I am happy" can be ‘escaped’ so that they are not treated as a part of the print syntax and can be treated like normal printable characters. Putting a backslash before the character indicates that the character needs to ‘escaped’ and printed as a normal character.

Here are a few examples which showcase the usage of backslash (\):

print "\"I am happy\", said Michael." # Escape the double quotes around the string "I am happy"

OUTPUT: "I am happy", said Michael.

Another example:

print 'I am 5\'4 tall' #Escape the single quote between 5 and 4

OUTPUT: I am 5'4 tall

Few other examples are as follows:

Example 1:

print '\'Python\''

OUTPUT: 'Python'

Example 2:

print '\"Python\"'

OUTPUT: "Python"

Another way to deal with printing single or double quotes is enclosing them within triple quotes:

print ''' "I am happy", said Michael. '''

OUTPUT: "I am happy", said Michael.

It is applicable only to strings that do not have triple quotes within the string as normal characters. If triple quotes are also present inside the string, backslash comes into play again. Look at the following example:

print ''' Triple quotes (''') are never used in written English'''

The above example gives an error, as the interpreter assumes that the triple quotes given within the bracket (''') indicate the end of the string. The problem can be solved using backslash again.

print ''' Triple quotes (\''') are never used in written English'''

OUTPUT: Triple quotes (''') are never used in written English

What if you want to print a backslash (\) as a part of a string?

Consider the following example for printing the string \Python\(including backslash)

Example: print "\Python\"

The above script gives an error and does not print the string \Python\. It is because the interpreter thinks that \" at the end of the string is an escape sequence and is an instruction to escape the double quote (") and print it.

Consider another example, in which you want to print the following statement as it is, including the backslash (\) character.

print "The backslash ' \' is not used in written English"

OUTPUT: The backslash ' ' is not used in written English

You can observe that the above script does not give an error, but does not give the desired output either. It does not print the ‘\’ character as it is, because again. it considers the character \' to be an escape sequence to escape the single quote(‘).Then, how do we print the backslash (\) character on the screen? For this purpose, we use another backslash character, which precedes the backslash to be printed. Consider the following examples for printing the string \Python\(including backslash)

Example 1:

print '\\Python\\'

OUTPUT: \Python\

The above example gives the correct script for printing backslash as a part of the string

Example 2:

print "The backslash '\\' is not used in written English"

OUTPUT: The backslash '\' is not used in written English.

Escape Sequences:

The following are some commonly used escape sequences supported by Python. As mentioned earlier, the escape character backslash (\) precedes certain characters to form an escape sequence.

Escape Sequence

What it performs

\\

prints backslash (\)

\'

prints single quote (')

\"

pints double quote (")

\'''

prints triple quote(''')

\b

ASCII backspace (BS).

\n

ASCII linefeed (LF). Inserts a new line.

\r

Carriage Return (CR)

\t

Horizontal Tab (TAB)

\v

ASCII vertical tab (VT)

Here is an example program which can which illustrates the usage of escape sequences

a = "\t I have tab space before me."

b = "My name is in the next line \n It is Michael."

c = "A sentence can be divided as: I \\ am \\ Michael."

d = """

About me:

\t* I am Michael

\t* I like Python

\t* It is very simple and\n\t* easy to learn

"""

print a

print b

print c

print d

Notice the tab spaces, backslashes and newlines you have specified.

OUTPUT:

I have tab space before me.

My name is in the next line

It is Michael.

A sentence can be divided as: I \ am \ Michael."

About me:

* I am Michael

* I like Python

* It is very simple and

* easy to learn

Execution:

Consider a simple sample program as follows:

#!/usr/bin/python

#Print on to the screen

print "hi. This is a python script"

The above script can be executed by typing python<space>filename.py

If the file name is samplescript, the execution is as follows:

Execution: python samplescript.py

Line indentation occupies a huge role in the construction of a block structure in Python. There are several simple rules to be followed while specifying the line indentation in Python. They are described in detail in the next chapter.