How To Tame Python

  • View

  • Download

Embed Size (px)



Text of How To Tame Python

  • 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.
  • Python was developed by Guido Van Rossum in the 80slate and early 90s. 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.
  • 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 WorldTrueIsnt 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 blocksinitiated 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:
  • 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.
  • 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
  • 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:
  • 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:
  • 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.
  • 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.