Linux

Basic Python Syntax

Now you have been introduced to basic saving and executing of program

You'll learn three things

Python Triple Quotes

example 1 give the demo of Triple Quotes

Example 1 :

print """
##______##____##__##________##
##______##____##__##___##___##
##______########__##__#__#__##
##____________##__##_#____#_##
######________##__##________##

"""

Out-put:
Python Triple Quotes
Triple Quotes
So Python triple quotes """ are more interactive. You can print same thing as in program by using triple quotes.

Python Back Slash \

The Python back slash \ use for continuation of print statement. You can stretch a single statement across multiple lines. See the example 2 below.

Example 2 :

print "Hello \
world "


Out-put:
Python Back Slash
Python Back Slash

String inside the quotes

For printing string you can use either a pair of single ( ' ') quotes or pair of double quotes (" "). Our next program clear your doubt.

Example 3 :

print "Hello World 'new' world"
print 'old world "but" still good'

Out-put:
Python Quotes
Quotes

Escape Sequence of String

Escape Sequnce allow you to put special characters such as the tab, the newline, and the backspace (delete key) into your strings. These give you greater control and flexibility
ESCAPESEQUENCE MEANING
\bBackspace
\aSound system bell
\nNewline
\tHorizontal tab
\\The \ character
\'Single quotation mark
\"Double quotation mark
Some escape sequences in Python
Let learn from one example

Example 4 :

print '\a'
print '\t\tPython'
print 'i know , you are \'great\' '

Out-put:
Escape sequence example
Escape sequence example
You can see the impact of above example. Have you heard the sound ? if not check you speakers.

Python String Concatenation

You can join two strings by using Python "+" operator.

Example 5 :

print "In this way you " + "can join 2 strings"

Out-put:
Concatenation of Strings

Python Formatted Output

Consider an example you want to print name, marks and age of person.
print "Name", "Marks", "Age"
print "Mohit", 80.67, "27"
print "Bhaskar", 76.908, "27"
print "Manish Pundir", 56.98, "25"
Out-put
Python Unformatted Out-put
Unformatted Out-put
You can see out-put, but output display is not nice. Python allows you to set formatted out-put. If you will have done some coding in C language. Then must be familiar with %d, %f, %s In order to represent int %d is used. %f for float and %s for string. If i used %5d means 5 spaces, if i used %5.2f means 5 spaces and .2 means precision. The decimal part of the number or the precision is set to 2, Let us formate new output.
print "Name Marks Age"
print ( "%s %14.2f %11d" % ("Mohit", 80.67, 27))
print ( "%s %12.2f %11d" %("Bhaskar" ,76.901, 27))
print ( "%s %3.2f %11d" %("Manish Pundir", 56.98, 25))
Out-put
Python formatted Out-put
formatted Out-put
The above out-put is better than previous one. You can see Marks 76.901 set to 76.90 automatically.






admin