how to tame python

18
How To Tame Python Learning Identifiers, Data types, Decisions, Looping, Functions, Modules, and File Handling in Python Author: Mohd Anwar Jamal Faiz Written: 23 rd November 2012 Email Id: [email protected] Website: http://www.meonshow.com/splash.php?uid=toughjamy Copyright: All rights reserved with Author. No part can be copied or circulated without written consent from the Author. About Author: I did B.Tech. in Computer Engineering from AMU, Aligarh. Thereafter, I pursued an Advanced Program in Project Management from IIM-Kozhikode. I have worked in Symantec Software, world's leading company in IT Security and backup. Earlier, I had worked in Adobe Systems Incorporated, world's leading Application Software, designing, and Animation products manufacturer. I started my career with Tata Consultancy Services, Asia's largest IT Service company, and worked there for 2 years dealing with US clients. I have strong technical proficiencies, rich creativity and excellent inter-personal skills. I have been trained from IITs, IIM, HAL, Microsoft, TCS, Adobe. I posses diverse industry and domain exposure, and my learning curve has always been very steep. I am a confident young professional; who is best at C++, VB, Python, HTML, .Net, PHP, Javascript, Shell, automations, Application testing, security testing, and performance testing, apart from having a rich collection of self composed poetry and inherent love for humanity. Expertise: C++, PHP, Python, HTML, Javascript, XML, Software Quality Assurance, Whitebox, API Testing, Application Testing, Penetration, Fuzzing, Static and Dynamic Code Analysis, Code Coverage, Scripting, and Automations on Windows [XP,Vista ,Server, 7,8], Linux, FreeBSD, Mac OSX, CentOS, Solaris etc. Overview of Python: Python is a High-level programming Language. Unlike C++ it is an interpreted language, though it maintains interactiveness and Object Oriented attributes. Python enjoys status of being a great scripting language for applications and automations, yet being a simple language in terms of constructs, structures, and style of programming. More often, you will hear statements like Python is Beginner's Language.

Upload: anwar-jamal

Post on 03-Sep-2014

776 views

Category:

Technology


8 download

DESCRIPTION

 

TRANSCRIPT

Page 1: How To Tame Python

How To Tame Python

Learning Identifiers, Data types, Decisions, Looping, Functions, Modules, and File

Handling in Python

Author: Mohd Anwar Jamal Faiz

Written: 23rd

November 2012 Email Id: [email protected] Website: http://www.meonshow.com/splash.php?uid=toughjamy Copyright: All rights reserved with Author. No part can be copied or circulated without

written consent from the Author. About Author: I did B.Tech. in Computer Engineering from AMU, Aligarh. Thereafter, I pursued

an Advanced Program in Project Management from IIM-Kozhikode. I have worked in Symantec Software, world's leading company in IT Security and backup. Earlier, I had worked in Adobe Systems Incorporated, world's leading Application Software, designing, and Animation products manufacturer. I started my career with Tata Consultancy Services, Asia's largest IT Service

company, and worked there for 2 years dealing with US clients. I have strong technical proficiencies, rich creativity and excellent inter-personal skills. I have been trained from IITs, IIM, HAL, Microsoft, TCS, Adobe. I posses diverse industry and domain exposure, and my learning curve has always been very steep. I am a confident young professional; who is best at

C++, VB, Python, HTML, .Net, PHP, Javascript, Shell, automations, Application testing, security testing, and performance testing, apart from having a rich collection of self composed poetry and inherent love for humanity.

Expertise: C++, PHP, Python, HTML, Javascript, XML, Software Quality Assurance, Whitebox, API Testing, Application Testing, Penetration, Fuzzing, Static and Dynamic Code Analysis, Code Coverage, Scripting, and Automations on Windows [XP,Vista ,Server, 7,8], Linux, FreeBSD, Mac OSX, CentOS, Solaris etc.

Overview of Python:

Python is a High-level programming Language. Unlike C++ it is an interpreted language, though it maintains interactiveness and Object Oriented attributes. Python enjoys status of being a great scripting language for applications and automations, yet being a simple language in terms of

constructs, structures, and style of programming. More often, you will hear statements like Python is Beginner's Language.

Page 2: How To Tame Python

Python was developed by Guido Van Rossum in the 80‟slate and early 90‟s. The up-to-date binaries and source code, together with documentation and bug lists is available at the official website of Python: http://www.python.org/. Python documentation can be downloaded from

www.python.org/doc/. The documentation is available in HTML, PDF, and other formats.

As you will proceed, you will find following characteristics of Python very attractive. You will be compelled to learn and tame the seemingly complex [just a myth!] language. The features are:

1. It is interpreted language, hence good for scripting. 2. It is easy to learn. Hence, a lot can be saved on training in Corporates. 3. It is now widely used and several plugins as per your need are available. 4. It yield a very readable and easy to maintain source code.

5. It can be easily connected with C APIs 6. Even the simple GUI development is easy. 7. It offers a broad and rich set of standard library. 8. The code is highly Portable, Scalable and Extendable

9. Compilers are available to convert code into different language eg. Jython to create Javascript. 10. Databases, Client Server, Object oriented, Complex data structures, are all easy to implement. And Last, but not the least, you have „How To Tame Python‟ guidebook freely available

So, let us start our journey of Taming the Python!

Identifiers and reserved words:

An identifier in any programming language is a name used to identify a variable, function, class,

module, or other objects. In Python, an identifier starts with a letter A to Z [uppercase or lower

case] or an underscore (_) followed by a combination of more letters, underscores, and digits (0-

9). It is important to note that Python is a case sensitive language. Also, punctuation characters

such as #, @, $, %, etc are not applicable in identifier name.

There are a list of words which are reserved in Python. Nearly all programming languages have a

list of reserved keywords. Following are reserved in Python:

class from print continue global raise def if with except break for pass elif return del import try and exec not assert finally or in while else is

More details can be learnt from the Official Python Document.

Page 3: How To Tame Python

Extended Hello World Program - First step in Taming the Python:

It has been a traditional way of teaching any programming language with first program as Hello

World printing. I will take liberty to start with a litt le more than a Hello World program. I call

this an Extended Hello World Program. This is actually aimed at giving you a first shot [Not a

free Vodka Shot ] of easiness with which a program can be written in Python.

The Output is as follows:

Hello World

True

Isn‟t it easy!!

You have already made a big step towards taming the Python. Printing anything has never been

so easier just a print statement does the magic. No imports or includes like Java, C++.

The next thing you can notice in the above code is that there are no „Programming blocks‟

initiated by Curly braces ({}. Rather the blocks in Python are maintained by the indentation used.

Improper indentations may yield syntax error and sometimes may lead to serious logical errors if

went un-noticed.

For example, the following code is correct:

But, the following code is wrong:

Page 4: How To Tame Python

Being an interpreted language, you will get an error as soon as Program Counter reaches at

execution of line with wrong indentation. Error generated is Syntax error.

Writing Comments in Python:

A hash sign (#) that does not exists inside a string literal begins a comment. All the characters

after the # and up to the end of line is regarded as a comment.

Eg.

#!/usr/sbin/python/code1

Or,

# This is a comment.

A comment can also be on the same line after a statement or expression. Eg.

Book=”How To Tame Python” # This is string having title of book.

Python also gives you a way to include a comment which expand for more than one line. The

comments or remarks can be kept in between 3 consecutive semicolon marks, before and the end

of any comment. For eg. Refer my First extended Hello World program comment.

Standard Data Types in Python - The Fangs of Python:

Python has five standard data types. Not to mention this is a very rich set and very easy to use. I

call these datatypes as fangs of the Python. As soon as you learn using and playing with them,

you will have no fear of Python.

Page 5: How To Tame Python

1. Numbers 2. String 3. List

4. Tuple 5. Dictionary

Let us see each of the above fangs of Python in detail:

Number - Fang 1:

This datatype is to store numerical values. Number objects are created as soon as you assign a

value to a variable.

For eg. Malihabad=1 GG=100

Going deeper, you will find that there are different numerical types namely int, long, float, and

complex. Yes, Python supports Complex Numbers too. This may set mathematics geeks dancing

on floor :)

Some examples are:

int

1, 2, 10, -3, 0x44, -035, or 8888 etc. Numbers starting with 0 are Octal numbers and 0x are Hexadecimal ones.

long

27042005L , 0xA345L, -38787676565L

float

Page 6: How To Tame Python

They are real floating point numbers eg. 15.20, -90.23, 8.32

complex

This is unique datatype to represent complex numbers directly, eg. 2+3j, -.65+39j

In the above code you can see the usage of numbers. See the output that came of the above

snippet.

Note: See carefully the str() function used before numerical variables. It is used for

concatenation of different datatype with the string. You will see in detail later. And, much

learning will happen only when you program in Python.

String – Fang 2

Strings in Python are identified as a contiguous set of alphanumeric characters in between a set

of quotation marks. This can be single quote, or a double quote. For eg. see the following

snippet:

Page 7: How To Tame Python

It is important to note that the indexing starts from 0 and goes to the Length of the string minus 1.

List - Fang 3

List is one of the most helpful and versatile data type available in Python. A list contains several

items separated by commas. The items are enclosed within square brackets ([]). The list comes

with built in functions which can be used to add, delete, edit contents in a list.

A typical list can be as simple as : list=[2,4,8,16,32], or

list2=['how','to','tame','python'], Or it can be a mix of datatypes for eg. list3=[1,'january' ,2.23,-3]

For a basic hands-on list refer the following code snippet:

Page 8: How To Tame Python

Note: Any subset of a list returned is also a list. Also note that like strings here also the Index

starts from 0 and goes to the Length of the list minus 1.

Tuple - Fang 4:

Tuple again is a data type that is similar to the list. However, elements of a tuple are enclosed

within parentheses. [Remember elements in a list were enclosed in square paranthesis]. It is

important to mention that a Tuple is a read-only list.

Page 9: How To Tame Python

Note: Any subset of a tuple returned is also a tuple. Also note that like strings, and list, here also

the Index starts from 0 and goes to the Length of the tuple minus 1.

Difference between List and Tuple

There is a great difference between Lists and Tuples. Tuples and Lists have always attracted the

learners of Python. And, to the most of employers, the difference between them still

maintains favoritism. Searching over the Internet gives you the distinction between them, but to

many the language used all over seems to not help much. And worse part is that, not all the

differences have ever been published at one place. And the worst of all, sometimes

technical slangs have been used, with no direct meaning or examples to make it clear.

Note: The most obvious difference is that Tuples are Immutable. Also, that Tuples are

heterogeneous while Listsare homogeneous. The differences have been duly discussed in

detailed in my blog. Visit the article at:

http://new-it-discussions.blogspot.in/2012/11/python-tuple-vs-list-difference.html

Page 10: How To Tame Python

Dictionary - Fang 5

Dictionaries in Python are like hash table. They include items as Key-Value Pair. They perform

with amazing effectiveness and come so handy that most of the complex data type jobs can be

done in minutes.

A simple construct of a dictionary in python is like following:

Dict1={'Key1': Value1, 'Key2': Value2, ......, KeyN: Value N}

For example, have a look into the following Code snippet:

So, after learning about the five Fangs of Python, you are in a position to try playing around with

Python. The next step would be to understand some simple programming constructs. Get a cup

of coffee before proceeding since this may be the final step of taming the Python.

Page 11: How To Tame Python

Programming Constructs in Python

Usually you are going to use if, else, elif, for, while loop etc for looping and decision making in

Python. They are simple and similar to other languages. But the best part is that in Python they

are as easy as writing an algorithm. That simply means that Python is hearing you in a more

informed way and you can tame the Python in a much more easy and human-understandable

way!!

These constructs are similar in their functioning, hence not much of my typing potential is being

spent on them. Practice more to play more with Python. After all, after taming the Python, it

becomes your pet!!

if statement:

The if statement and following variants of if are used for decision making. The syntax of the if

statement is:

if expression: statement(s)

if-else statement:

The syntax of the if...else block is:

if expression: statement(s)

else: statement(s)

elif statement

It is a name give to elseif statement. The syntax is:

if expression1:

statement(s) elif expression2: statement(s)

Page 12: How To Tame Python

elif expression3: statement(s) else:

statement(s)

Note: You can also create a Nested if...elif...else programming construct like following

if expression1: statement(s) if expression2:

statement(s) elif expression3: statement(s) else

statement(s) elif expression4: statement(s) else:

statement(s)

The while Loop:

This construct is used for looping purposes. The syntax of the while is:

while expression: statement(s) This means that statement(s) will be executed untill the expression holds True.

For Loop:

This programming construct is again used for looping purpose. The syntax of the for loop is:

for counter in sequence: statements(s)

Page 13: How To Tame Python

The following programming example would make you understand the usage of above constructs:

Let me take the pleasure of explaining what is happening in the above code. The loop continues

from 1 to 49. In between these numbers whenever any multiple of 5 is encountered it is printed.

Functions and Modules – Sitting on Python

After having equipped with knowledge of basic programming constructs we now move on to

making and using functions. At the same time we will also see what a module is, and how is it

used.

A User defined function in python is done by a keyword 'def'. For eg. let us try to make a

function that takes a number as input parameter and prints it.

def printNumber( n ): "Following is the number" print n return

Page 14: How To Tame Python

Calling a Function is simply using its name, and passing the rquired parameters if any. For eg.

above function can be called in one of following ways:

printNumber(4), or printNumber(45*7)

For the benefit of my readers I am including a code segment that uses a function to print only

even numbers between 1 to 20 (both inclusive):

In the above example we can see that a function with the name isEven has been created. This

function will return True if the number passed to it is Even and False if it is Odd. A while loop is

constructed to loop from 1 to 20, and each incremented value of the iterator is being checked

using our constructed function. If the result returned from our function is True, then the number

is printed. Mission accompalished!

The next logical meaning to functions and its implementaion is given using Modules. A module

allows logical organization of your Python code. A module can simply be thought as a file

consisting of Python code. A module can define functions, classes, and variables. It may also

include runnable code.

Page 15: How To Tame Python

For eg.

Let us name a file check.py. The content of file is as follows:

Now let us try to use this file in another program.

Open a new Python file. Name it try.py , for instance. In order to use the functions in check.py

you need to import that module. The statement use to do that is import. The syntax is:

import <module name>

When the Python interpreter encounters an import statement, it imports the module if the module

is present in the search path of program execution. A search path is a list of directories that the

interpreter searches before importing a module.

Page 16: How To Tame Python

In a similar fashion, there are some predefined modules in python. They can be regarded as

library functions of python. For example one of the most handy module is os module. You will

learn about that and much more in the complete documentation of Python available at

www.python.org/doc/

So, with this we come to an end of basic session on modules and its usage.

Opening, Closing, and Writing a File – Playing with Python

Comeon, obviously I am joking.. Python is a vast language. You need much more knowledge.

But, I am pretty much sure, that once you learn how to open, close, and edit a file, you have

already become well conversant with the language. The only thing that remains now is Practice.

And as the saying goes: Practice makes a man perfect. Hence as of now, it is important to learn

that art of file handling.

Opening a file:

Before anything you can read or write a file, you have to open it. For this come built-in open()

function. This is stored in a built-in module. This function creates a file object that will be

utilized to call other support functions.

Syntax:

For all normal File related operations, you need to know the following syntax.

file <handle name> = open(file_name [, access_mode])

Here are the parameters and their meaning:

file_name: Name of the file that you want to access. access_mode: Mode ie. read, write append etc. Default file access mode is read (r).

Page 17: How To Tame Python

Other available modes are:

r Open a file for reading only.

rb Open a file for reading only in binary format. r+ Open a file for both reading and writing. rb+ Open a file for both reading and writing in binary format. w for writing only. Overwrite file if the file exists. If file does not exist, create a new file.

wb for writing only in binary format. Overwrite file if the file exists. If file does not exist, create a new file. w+ for both writing and reading. Overwrite the exist ing file if the file exists. If file does not exist, create a new file.

wb+ for both writing and reading in binary format. Overwrite existing if the file exists. If file does not exist, create a new file a for appending. The file pointer is at the end of the file if the file exists. If file does not exist, it creates a new file.

ab for appending in binary format. file pointer is at end of file if file exists. If the file does not exist, it creates a new file a+ Open a file for both appending and reading. All characteristic of mode 'a' also holds true. ab+ Open a file for both appending and reading in binary format. All characteristic of mode 'a'

also holds true.

Closing a file: This is done using the close() Method. This flushes or discards any unwritten information in the file and closes the file object, after which no more writing can be done. Eg. fileObject.close();

Reading and Writing Files:

The write() Method is used to write in a file. Eg. fileObject.write(string); The read() Method is used to read a file. Eg. fileObject.read([count]);

Let us see a final Program illustrating the file handling in Python: To start with let us assume that there is a file named „abc.txt‟ present at the same location as the following python code file. The initial text present in file is “abc”. We are performing several

actions on „abc.txt‟ and the effect is shown by the output of the program.

Page 18: How To Tame Python

First we read the file and the initial output is “abc” on the console. With second opening in write mode overwrites the file and the final text is “Anwar Jamal” and the string present in the file i.e“abc” gets lost. Thereafter, the append mode adds the string “How To Tame Python”. Hence the final string in the file becomes concatenated string of last two stages. This can also be seen as

the output when the file is read again in read mode. So now, Python has started helping you in your File handling tasks also. You can read files,

parse, operate on results, and create new files. You have learnt making decisions and looping in Python. You have learnt making Functions and using modules. To put it in a simple way, you have learnt the basic usage of Python as a Scripting and Automation Tool. You now know how to make Python assist you in your development and testing efforts. So, should not I say that you

have tamed the Python!! With this, I come to an end of this guidebook – “How To Tame Python”. Please feel free to send

your feedback to [email protected]. M o h d A n w a r J a m a l F a i z - 0 0 9 1 - 8 8 8 8 3 2 7 6 5 8 - P u n e - I n d ia