Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Learn Python in 7 Days

You're reading from   Learn Python in 7 Days Begin your journey with Python

Arrow left icon
Product type Paperback
Published in May 2017
Publisher Packt
ISBN-13 9781787288386
Length 280 pages
Edition 1st Edition
Languages
Arrow right icon
Authors (2):
Arrow left icon
Mohit Raj Mohit Raj
Author Profile Icon Mohit Raj
Mohit Raj
Bhaskar N. Das Bhaskar N. Das
Author Profile Icon Bhaskar N. Das
Bhaskar N. Das
Arrow right icon
View More author details
Toc

Table of Contents (12) Chapters Close

Preface 1. Getting Started with Python FREE CHAPTER 2. Type Variables and Operators 3. Strings 4. Lists 5. Dictionary 6. Control Statements and Loops 7. Function and Scope of Variable 8. Modules and Packages 9. File Handling and Exceptions 10. Collections 11. Class and Objects

Basic Python syntax

Basic syntaxes can be referred to as simple guidelines that every programming language requires. Let's try to understand from our daily lives. Let's say you can't eat your food without having it dressed and placed properly on the platter. You need to have proper dressing of food before you can consume it. You prepare a special drink comprising three measures of Gordon gin, one of vodka, half of Kina Lillet, and follow the process to mix in steps. The process is necessary to have a perfect blend. These are sort of syntaxes when we talk in terms of programming languages.

Kina Lillet-Lillet (French pronunciation: [li'le]), classed as an aromatized wine within EU law, is a French aperitif wine from Podensac, a small village south of Bordeaux. It is a blend of 85% Bordeaux region wines (Semillon for the Blanc and for the Rosé, Merlot for the Rouge) and 15% macerated liqueurs, mostly citrus liqueurs (peels of sweet oranges from Spain and Morocco and peels of bitter green oranges from Haiti). The mix is then stirred in oak vats until blended. During the aging process, Lillet is handled as a Bordeaux wine (undergoing fining, racking, filtering, and so on).
The preceding information has been taken from https://en.wikipedia.org/wiki/Lillet.

Comments in Python

In Python, there are two types of comments--one is a single-line comment and the other is multiline comment. For a single-line comment, # is used, while for a multiline comment, triple quotes """ are used:

#This is a single line comment in Python

print "Hello World" #This is a single comment in Python

""" For multi-line
comment use three
double quotes
...
"""
print "Hello World!"

Triple, double and single quotes

Python doesn't care if you use single quotes or double quotes to print a single statement. But, surely, both has some significance while printing complex statements, which we will see soon.

print "Hello World!" and print 'Hello World!' will give the same output Hello World! two times:

How will you print something like this:

I am mad in love  do you think  I am doing the right thing? One way is to enclose the complete thing within the triple quotes as shown here:
print '''I am mad in love
do you think
I am doing
the right thing '''

Alternatively, you can also use double quotes three times to achieve the same thing:

print """I am mad in love
do you think
I am doing
the right thing """
The preceding two examples are not in formatted form, they are just to show how we can achieve multiline printing.

Let's try another example. What should be the outcome of the following statement?

print 'Hey there it's a cow'

The preceding piece of code gives the following results:

C:pydev>python hello.py
File "hello.py", line 1
print 'Hey there it's a cow'
^
SyntaxError: invalid syntax

Python simply interprets that the statement terminated with a single quote after it. The solution is to enclose the complete sentence within double quotes as shown:

print "Hey there it's a cow"

Adding double quotes (") gives an error-free output as shown:

C:pydev>python hello.py
Hey there it's a cow

Python back slash

The Python back slash is used for continuation of the print statement. You can stretch a single statement across multiple lines:

print "Hello
world "

This gives the following output:

C:pydev>python hello.py
Hello world

String inside the quotes

For printing a string, either a pair of single (' ') quotes or pair of double quotes (" ") can be used as shown in the succeeding examples: 

print "Hello World 'Mr' Bond"
print 'old world "but" still good'

This gives the following results:

C:pydev>python hello.py
Hello World 'Mr' Bond
old world "but" still good

Escape sequence in Python

The escape sequence is used to insert the tab, the newline, the backspace, and other special characters into your code. They give you greater control and flexibility to format your statements and code:

Escape Sequence Meaning
b Backspace
a Sound system bell
n Newline
t Horizontal tab
The character
' Single quotation mark
" Double quotation mark
print 'a' 
print 'tHermit'
print "i know , they are 'great'"

The output is as follows:

C:pydev>python hello.py
Hermit
i know , they are 'great'

The preceding code executes with a beep sound. If you did not hear the beep sound, check your speakers.

String concatenation

Two strings can be joined using the + operator:

print "Only way to join" + "two strings"

The following is the output of the preceding code:

C:pydev>python string_concatenation.py
Only way to join two strings

Formatted output

Consider an example where you would want to print the name, marks, and the age of the person:

print "Name", "Marks", "Age" 
print "John Doe", 80.67, "27"
print "Bhaskar", 76.908, "27"
print "Mohit", 56.98, "25"

The output will be as follows:

C:pydev>python hello.py
Name Marks Age
John Doe 80.67 27
Bhaskar 76.908 27
Mohit 56.98 25

You can see the output, but the output that is displayed is not formatted. Python allows you to set the formatted output. If you have done some coding in C language, then you should be familiar with %d, %f, %sIn order to represent an integer %d is used, %f is used for float, and %s is used for string. If you used %5d, it means 5 spaces. If you used %5.2f, it means 5 spaces and .2 means precision. The decimal part of the number or the precision is set to 2. Let's use the formatting on the preceding example:

print "Name Marks Age" 
print ( "%s %14.2f %11d" % ("John Doe", 80.67, 27))
print ( "%s %12.2f %11d" %("Bhaskar" ,76.901, 27))
print ( "%s %3.2f %11d" %("Mohit", 56.98, 25))

The output we get is as follows:

C:pydev>python hello.py
Name Marks Age
John Doe 80.67 27
Bhaskar 76.90 27
Mohit 56.98 25

The preceding output is much better than the previous one. You can see Marks 76.901 set to 76.90 automatically.

Indentation

The most unique characteristic of Python, unlike other programming languages, is indentation. Indentation not only makes Python code readable, but also distinguishes each block of code from the other. Let's explain this with an example:

def fun():
pass
for each in "Australia":
pass

While writing the code, a new block of code starts with a colon followed by a tab. Here, after the function fun(), a colon is provided which will start the function body, pass is part of the function fun() and it is placed at one tab space. Likewise, the for loop starts with a colon. Here, most people get confused whether to use a tab or space. It is advisable to stick to only one type and follow the same across the whole code. If the indentation is not strictly implemented, then code execution will throw an error.

You have been reading a chapter from
Learn Python in 7 Days
Published in: May 2017
Publisher: Packt
ISBN-13: 9781787288386
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime
Banner background image