Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

How To Tame Python


Published on

Published in: Technology
  • Login to see the comments

How To Tame Python

  1. 1. How To Tame PythonLearning Identifiers, Data types, Decisions, Looping, Functions, Modules, and File Handling in PythonAuthor: Mohd Anwar Jamal FaizWritten: 23rd November 2012Email Id: Toughjamy@yahoo.comWebsite: All rights reserved with Author. No part can be copied or circulated withoutwritten consent from the Author.About Author: I did B.Tech. in Computer Engineering from AMU, Aligarh. Thereafter, I pursuedan Advanced Program in Project Management from IIM-Kozhikode. I have worked in SymantecSoftware, worlds leading company in IT Security and backup. Earlier, I had worked in AdobeSystems Incorporated, worlds leading Application Software, designing, and Animation productsmanufacturer. I started my career with Tata Consultancy Services, Asias largest IT Servicecompany, and worked there for 2 years dealing with US clients. I have strong technicalproficiencies, 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 mylearning curve has always been very steep. I am a confident young professional; who is best atC++, VB, Python, HTML, .Net, PHP, Javascript, Shell, automations, Application testing,security testing, and performance testing, apart from having a rich collection of self composedpoetry 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 CodeAnalysis, 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, thoughit maintains interactiveness and Object Oriented attributes. Python enjoys status of being a greatscripting language for applications and automations, yet being a simple language in terms ofconstructs, structures, and style of programming. More often, you will hear statements likePython is Beginners Language.
  2. 2. Python was developed by Guido Van Rossum in the 80‟slate and early 90‟s. The up-to-datebinaries and source code, together with documentation and bug lists is available at the officialwebsite of Python: Python documentation can be downloaded The documentation is available in HTML, PDF, and other formats.As you will proceed, you will find following characteristics of Python very attractive. You willbe 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 APIs6. 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 Extendable9. 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 lowercase] 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 characterssuch as #, @, $, %, etc are not applicable in identifier name.There are a list of words which are reserved in Python. Nearly all programming languages have alist of reserved keywords. Following are reserved in Python:class from print continue global raise def if with except break for passelif return del import try and exec not assert finally or in while else isMore details can be learnt from the Official Python Document.
  3. 3. 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 HelloWorld printing. I will take liberty to start with a little more than a Hello World program. I callthis an Extended Hello World Program. This is actually aimed at giving you a first shot [Not afree Vodka Shot ] of easiness with which a program can be written in Python.The Output is as follows:Hello WorldTrueIsn‟t it easy!!You have already made a big step towards taming the Python. Printing anything has never beenso 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 ifwent un-noticed.For example, the following code is correct:But, the following code is wrong:
  4. 4. Being an interpreted language, you will get an error as soon as Program Counter reaches atexecution 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 charactersafter the # and up to the end of line is regarded as a comment.Eg.#!/usr/sbin/python/code1Or,# 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. Thecomments or remarks can be kept in between 3 consecutive semicolon marks, before and the endof 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. Icall these datatypes as fangs of the Python. As soon as you learn using and playing with them,you will have no fear of Python.
  5. 5. 1. Numbers 2. String 3. List 4. Tuple 5. DictionaryLet 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 avalue to a variable.For eg.Malihabad=1GG=100Going deeper, you will find that there are different numerical types namely int, long, float, andcomplex. Yes, Python supports Complex Numbers too. This may set mathematics geeks dancingon floor :)Some examples are:int1, 2, 10, -3, 0x44, -035, or 8888 etc.Numbers starting with 0 are Octal numbers and 0x are Hexadecimal ones.long27042005L , 0xA345L, -38787676565Lfloat
  6. 6. They are real floating point numbers eg.15.20, -90.23, 8.32complexThis is unique datatype to represent complex numbers directly, eg.2+3j, -.65+39jIn the above code you can see the usage of numbers. See the output that came of the abovesnippet.Note: See carefully the str() function used before numerical variables. It is used forconcatenation of different datatype with the string. You will see in detail later. And, muchlearning will happen only when you program in Python.String – Fang 2Strings in Python are identified as a contiguous set of alphanumeric characters in between a setof quotation marks. This can be single quote, or a double quote. For eg. see the followingsnippet:
  7. 7. It is important to note that the indexing starts from 0 and goes to the Length of the string minus 1.List - Fang 3List is one of the most helpful and versatile data type available in Python. A list contains severalitems separated by commas. The items are enclosed within square brackets ([]). The list comeswith 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], orlist2=[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:
  8. 8. Note: Any subset of a list returned is also a list. Also note that like strings here also the Indexstarts 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 enclosedwithin parentheses. [Remember elements in a list were enclosed in square paranthesis]. It isimportant to mention that a Tuple is a read-only list.
  9. 9. Note: Any subset of a tuple returned is also a tuple. Also note that like strings, and list, here alsothe Index starts from 0 and goes to the Length of the tuple minus 1.Difference between List and TupleThere is a great difference between Lists and Tuples. Tuples and Lists have always attracted thelearners of Python. And, to the most of employers, the difference between them stillmaintains favoritism. Searching over the Internet gives you the distinction between them, but tomany the language used all over seems to not help much. And worse part is that, not all thedifferences have ever been published at one place. And the worst of all, sometimestechnical 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 areheterogeneous while Listsare homogeneous. The differences have been duly discussed indetailed in my blog. Visit the article at:
  10. 10. Dictionary - Fang 5Dictionaries in Python are like hash table. They include items as Key-Value Pair. They performwith amazing effectiveness and come so handy that most of the complex data type jobs can bedone 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 withPython. The next step would be to understand some simple programming constructs. Get a cupof coffee before proceeding since this may be the final step of taming the Python.
  11. 11. Programming Constructs in PythonUsually you are going to use if, else, elif, for, while loop etc for looping and decision making inPython. They are simple and similar to other languages. But the best part is that in Python theyare as easy as writing an algorithm. That simply means that Python is hearing you in a moreinformed way and you can tame the Python in a much more easy and human-understandableway!!These constructs are similar in their functioning, hence not much of my typing potential is beingspent on them. Practice more to play more with Python. After all, after taming the Python, itbecomes your pet!!if statement:The if statement and following variants of if are used for decision making. The syntax of the ifstatement is:if expression: statement(s)if-else statement:The syntax of the if...else block is:if expression: statement(s)else: statement(s)elif statementIt is a name give to elseif statement. The syntax is:if expression1: statement(s)elif expression2: statement(s)
  12. 12. elif expression3: statement(s)else: statement(s)Note: You can also create a Nested if...elif...else programming construct like followingif 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)
  13. 13. 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 continuesfrom 1 to 49. In between these numbers whenever any multiple of 5 is encountered it is printed.Functions and Modules – Sitting on PythonAfter having equipped with knowledge of basic programming constructs we now move on tomaking and using functions. At the same time we will also see what a module is, and how is itused.A User defined function in python is done by a keyword def. For eg. let us try to make afunction that takes a number as input parameter and prints it.def printNumber( n ): "Following is the number" print n return
  14. 14. 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), orprintNumber(45*7)For the benefit of my readers I am including a code segment that uses a function to print onlyeven numbers between 1 to 20 (both inclusive):In the above example we can see that a function with the name isEven has been created. Thisfunction will return True if the number passed to it is Even and False if it is Odd. A while loop isconstructed to loop from 1 to 20, and each incremented value of the iterator is being checkedusing our constructed function. If the result returned from our function is True, then the numberis printed. Mission accompalished!The next logical meaning to functions and its implementaion is given using Modules. A moduleallows logical organization of your Python code. A module can simply be thought as a fileconsisting of Python code. A module can define functions, classes, and variables. It may alsoinclude runnable code.
  15. 15. For eg.Let us name a file 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 , for instance. In order to use the functions in check.pyyou 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 moduleis present in the search path of program execution. A search path is a list of directories that theinterpreter searches before importing a module.
  16. 16. In a similar fashion, there are some predefined modules in python. They can be regarded aslibrary functions of python. For example one of the most handy module is os module. You willlearn about that and much more in the complete documentation of Python available, with this we come to an end of basic session on modules and its usage.Opening, Closing, and Writing a File – Playing with PythonComeon, 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 havealready 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 learnthat 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 beutilized 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).
  17. 17. 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 existing file if the file exists. If file does notexist, create a new file.wb+ for both writing and reading in binary format. Overwrite existing if the file exists. If filedoes not exist, create a new filea for appending. The file pointer is at the end of the file if the file exists. If file does notexist, it creates a new file.ab for appending in binary format. file pointer is at end of file if file exists. If the file doesnot exist, it creates a new filea+ 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 aalso holds true.Closing a file:This is done using the close() Method. This flushes or discards any unwritten information in thefile 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.[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 thefollowing python code file. The initial text present in file is “abc”. We are performing severalactions on „abc.txt‟ and the effect is shown by the output of the program.
  18. 18. First we read the file and the initial output is “abc” on the console. With second opening in writemode overwrites the file and the final text is “Anwar Jamal” and the string present in the filei.e“abc” gets lost. Thereafter, the append mode adds the string “How To Tame Python”. Hencethe final string in the file becomes concatenated string of last two stages. This can also be seen asthe 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 inPython. You have learnt making Functions and using modules. To put it in a simple way, youhave learnt the basic usage of Python as a Scripting and Automation Tool. You now know howto make Python assist you in your development and testing efforts. So, should not I say that youhave tamed the Python!!With this, I come to an end of this guidebook – “How To Tame Python”. Please feel free to sendyour feedback to o h d A n w a r J a ma 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