Book Image

Learn Python in 7 Days

Book Image

Learn Python in 7 Days

Overview of this book

Python is a great language to get started in the world of programming and application development. This book will help you to take your skills to the next level having a good knowledge of the fundamentals of Python. We begin with the absolute foundation, covering the basic syntax, type variables and operators. We'll then move on to concepts like statements, arrays, operators, string processing and I/O handling. You’ll be able to learn how to operate tuples and understand the functions and methods of lists. We’ll help you develop a deep understanding of list and tuples and learn python dictionary. As you progress through the book, you’ll learn about function parameters and how to use control statements with the loop. You’ll further learn how to create modules and packages, storing of data as well as handling errors. We later dive into advanced level concepts such as Python collections and how to use class, methods, objects in python. By the end of this book, you will be able to take your skills to the next level having a good knowledge of the fundamentals of Python.
Table of Contents (18 chapters)
Title Page
Credits
About the Authors
About the Reviewer
www.PacktPub.com
Customer Feedback
Preface
2
Type Variables and Operators

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.

Note

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

 

Note

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, %s. In 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 Marks76.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.