Jump to content

Introduction to Python Programming/Printable version

From Wikibooks, open books for an open world


Introduction to Python Programming

The current, editable version of this book is available in Wikibooks, the open-content textbooks collection, at
https://en.wikibooks.org/wiki/Introduction_to_Python_Programming

Permission is granted to copy, distribute, and/or modify this document under the terms of the Creative Commons Attribution-ShareAlike 3.0 License.

Introduction

Python is free and open source software that is available at free of cost to the end user where the end user can develop, modify, reengineer, and distribute versions of the software under the general public license which is at the disposal of other end users.

Python is dynamic and strongly typed language. Variables are assigned the types on their first initialization of the value i.e., variables are assigned dynamically during run time instead of having to declare them first and use them later as done in the statically typed languages such as C, C++, Java. Languages such as C, C++, Java, etc require that variables are first declared, initialized and then utilized within the programs that they are run, in contrast to Python. This holds true for all things including parameters, functions, methods, and classes. Python allows for object oriented programming just like Java, C, C++, etc. Python tracks all the variables at run time and reports any discrepancies within code, variables the moment it senses it.

There is no need for extra curly braces, semicolons, the need to compile the program and then run the program as one needs to be do in C, C++, Java programming. Python interpreter tracks the errors of the code blocks at run time and throws up error the moment it senses an error opposed to the typical statically typed languages where error checking happens at compile time. With statically typed languages, it’s a pain staking process wherein one needs to type out the entire code block and then compile it to check for any errors.

Python offers a shell interpreter where small pieces of code can be tested without having to write out entire pieces of code. The shell interpreter saves a lot of time in testing individual blocks of code allowing for simultaneous checking of code, testing it, and debugging it.

Python files can be imported easily into the shell interpreter with a single command, allowing access to the methods, classes, and instances of the Python modules which allows for greater reusability of code.

Python provides inbuilt testing modules that allow the end user to develop testing code units resulting in Test Driven Development (TDD). This flexibility allows user to not only test, debug code while it is being written, but allows test for errors the moment the code gets written. All types of testing, including functional testing, black box testing, extra can be performed easily.

Python programming language is suited for both front end development, and back end processes. Python is suited for a myriad purposes including but not limited to data processing, Graphical User Interfaces (GUI), running background processes, real time processing of data, running numerical simulations.

Further Python allows for development within specific extensions that can be imported making Python flexible for a variety of applications. The applications of Python as a programming languages used to develop applications are endless and are left to the user’s imagination to come with innovative applications.

Some examples of extensions of Python that allow extra capabilities are Numpy that offer matlab type of capabilities providing for array operations, matplotlib that is the Python library for plotting high quality graphs, and pandas that provides high performance, easy to use data structures, and data analysis tools. Stunning visualizations can also be made from real data.

This book on Python is intended to be primer allowing the user to learn the basics of Python programming without getting into the intricate details of the language or the benefits it offers. The benefits become aware to the user as and when the user learns the language.

While I have exalted the features of Python programming, there are some downsides associated with Python programming. One of the major downside is that Python is that it is not memory optimized like C, or C++ which may lead to extra run time problems or increased execution times. However, the features of Python provide for attractive propositions than any other existing languages can offer and hence is the most preferred languages for a variety of applications


Python Programming - Installing Python

Chapter 2: Installing Python

[edit | edit source]

Here in this chapter, I will tell you about installing Python on your local machine. There are two versions of Python available from the main Python website namely the Python 2.7.XXXX and Python 3.0.XXX. I prefer to use, teach Python 2.7.XXX versions. In this book, I will be talking, and writing about Python 2.7.XXX. What’s the difference, one may questions. There are differences between the two versions with syntax and a few other minor changes.

Coming to the question, which Python is right for you?

Python like any other open source software is a constantly evolving where the users from all over the world are contributing, making and updating features. There is a board of members that vote on a particular feature and decide whether the feature needs to be integrated or not. The documentation that acts as the supporting is constantly evolving at the same time. So decide on which one you want to use depending on your preferences and evaluations.

That said, it’s more than enough that you know one of these either versions, knowing one will make it a breeze to know the other versions. Just keep that in mind, and start talking Python.

After deciding which version of Python to learn, the first thing you need to do with Python is install it.

2.1. Installing version of Python

[edit | edit source]

After you have decided which version of Python to learn, you need to install it. Linux and Mac OSX machines come with preinstalled Python packages so you need not worry about installing. Run the command terminal and type in the keyword python, and the machine will tell you if you have Python installed or not. Go figure that, Good luck with that!

Since I have only a Windows machine, I will guide you through installing Python on a Windows computer. Go figure

As a matter of fact, Windows does not come with Python pre installed. Go ahead and download the version of Python software that you want to use from the Python official website.

Installing Python from Python dot org

  1. Download the latest Python Windows installer by going to http://www.python.org/ftp/python/ and selecting the highest version number listed, then downloading the .exe installer.
  2. Double-click the installer, Python-2.xxx.yyy.exe. The name will depend on the version of Python available when you read this.
  3. Make sure that you have the administrative rights on the machine that you are working on.
  4. Step through the installer program.
  5. Some of the features can be removed from the installation in case you do not have enough space on your hard disk.
  6. Python will be installed with all the proper files and extensions.
  7. After the installation is complete, close the installer and select Start->Programs->Python 2.7->IDLE (Python GUI). You'll see something like the following, which is a sample shot from my machine:
   Python 2.7.11 (v2.7.11:6d1b6a68f775, Dec 5 2015, 20:32:19) [MSC v.1500 32 bit (Intel)] on win32
   Type "copyright", "credits" or "license ()" for more information.
   >>> 

I am assuming that you have the standard Python interpreter on the machine that you are currently planning to work on with.

2.2. The Interactive Shell

[edit | edit source]

Once you have Python installed, there are different ways to run Python programs. On the shell interpreter, you can run commands and test how the flow of code goes. You can save the code that you have written and then run the file to obtain the output for the code that you have written.

Here, I will explain how to run simple code snippets on the Python interpreter.

You can fire up the Python shell interpreter in any of the following ways.

2.2.1. Method 1:

[edit | edit source]

Run the command interpreter by pressing the windows and the letter R. You will see a window open up like this.

Type in the letters cmd in the text box and you will see a screen like the one shown below in Figure 2.

Once at the command prompt, change into the directory where the Python executable resides. For example, on my local machine, I have the Python executable residing on C:\Python27\. So, I will go ahead and change into that particular folder by typing “cd C:\Python27” on the command prompt. Here’s what I see on my local machine. Once inside the folder Python27, type in python at the command prompt and voila! You’ll see the Python shell interpreter as illustrated in Figure 3.

2.2.2. Method 2:

[edit | edit source]

Now there is a second way on firing the Python shell interpreter and the following will explain how to do the same. Click on Start-> All Programs->Python2.7->Python IDLE and you’ll see the following shell interpreter as shown in Figure. 4.

Feel comfortable with these methods of firing up Python shell interpreter, I will talk about different other methods of firing the shell interpreter as and when the situation rises for the occasion. Here IDE stands for Integrated Development Editor, this is the Graphical User Interface (GUI) of the Python programming paradigm.

Apparently, there are users who use the Python shell interpreter like a calculator, but I still stick my own calculator on my local Windows machine.

Just type in the following command in the Python shell interpreter and you will see the following result. For sake of understanding, the input commands to the shell interpreter are preceded with >>>, while the output from the shell interpreter is in “Burnt Sienna” color. 
   >>> print "Hello World!!!!"
   Hello World!!!!
   >>>

There is one important operator that anyone needs to know which is the “=” operator also called the assignment operator. Variables can be assigned values using the assignment operator and Python will dynamically typecast the variable based on the value assigned to the variable.

Launch the Python interactive shell in whatever way works on your platform, and let's dive in with the steps shown here:

Example 1. First Steps in the Interactive Shell

   >>> print "Hello World, my first Python Program"
   Hello World, my first Python Program
   >>> 6+7
   13 
   >>> x = 4               
   >>> y = 6
   >>> x + y
   10

Welcome to the Python party! Lets Python like we have never Python”ed before.

2.3. Kick starting with Python

[edit | edit source]

There is another way to achieve printing “Hello World” like shown in the earlier sections. Store the value “Hello World” in a variable and then print the variable. The output of the print statement are followed by the outputs that they provide just below them

   >>> s="Hello World!"
   >>> s
   'Hello World!'
   >>> print (s)
   Hello World!
   >>> print s
   Hello World!

To write multiple lines, just add ‘\n’ character where you want to introduce the new line. Just follow the following example.

   >>> print "This is the first line\nAnd this is the second line"
   This is the first line
   And this is the second line
   >>> mystring="This is the first line\nAnd this is the second line"
   >>> mystring
   'This is the first line\nAnd this is the second line'
   >>> print mystring
   This is the first line
   And this is the second line

2.3.1. Printing variables

[edit | edit source]

Variables can be printed in their forms and also the types they are cast into can also be printed using the print command. To print variables,

   >>> x=3
   >>> x
   3
   >>> print x
   3
   >>> print (x)
   3
   >>> print (str(x))
   3
   >>> print type(x)
   <type 'int'>

The above print statements focused on printing a single variable. However, a combination of different variables can be printed using a same single print command.

   >>> x=5
   >>> y=7
   >>> print x
   5
   >>> print y
   7
   >>> print x,y
   5 7
   >>> print (x,y)
   (5, 7)

Before printing integer variables, they have to be converted to string type using the str when printing along with string variables.

   >>> print str(x) + str(y)
   57
   >>> print str(x) + " " + str(y)
   5 7
   >>> print x+7
   12
   >>> print x+y
   12
   >>> print (x+y)
   12
   >>> print "the sum of %d and %d is %d" %(x,y,x+y)
   the sum of 5 and 7 is 12

2.3.2. Getting text inputs

[edit | edit source]

Obtaining input from the interpreter into the shell is done using the input command available. The syntax and the following statements highlight the use of input commands. Strings inputs have to be enclosed within quotes. Errors are highlighted in red.

   >>> input("what is the number")
   what is the number3
   3
   >>> input("whats my name!:")
   whats my name!:Some
   Traceback (most recent call last):
     File "<pyshell#52>", line 1, in <module>
       input("whats my name!:")
     File "<string>", line 1, in <module>
   NameError: name 'Some' is not defined
   >>> input("whats my name!:")
   whats my name!:"New Name"
   'New Name'
   >>> name=input("whats my name!:")
   whats my name!:"New Name"
   >>> print name
   New Name
   >>> print (name)
   New Name
   >>> print "My name is " + name
   My name is New Name
   Python typecasts the variable based on the input you provide the Python interpreter. 
   >>> print "My name is " + name
   My name is New Name
   >>> age=input("whats my name!:")
   whats my name!:34
   >>> print age
   34
   >>> print type(name)
   <type 'str'>
   >>> print type(age)
   <type 'int'>
   >>> print type(name), type(age)
   <type 'str'> <type 'int'>
   >>> print "The data type of "+ name +" and "+str(age)+"is "+ str(type(name)) + "and " + str(type(age))
   The data type of New Name and 34is <type 'str'>and <type 'int'>

However for ease of use, you can specifically instruct the Python interpreter to typecast the input into the type of variable you want to use the variable in. if you don’t specifically provide the typecast, Python interpreter will do the job of typecasting the variable.

   >>> x=int(input("enter a integer number"))
   enter a integer number3
   >>> x
   3
   >>> x=float(input("enter a integer number"))
   enter a integer number4
   >>> print x
   4.0
   >>> x
   4.0
   >>> x=str(input("enter a integer number"))
   enter a integer number4
   >>> x
   '4'
   >>> x=input("enter a integer number")
   enter a integer number5
   >>> x
   5
   >>> print type(x)
   <type 'int'>

Now that we have a fair idea of the print and the input commands, let’s write a simple Python program that will ask your name, age, location, and your job details and prints the same. On the Python interpreter, I opened a new file and wrote the following piece of code and saved it as file.py.

   name=input("Enter your name: ")
   age=input("Enter a two digit number as age: ")
   location=input("Enter your current location: ")
   job=input("Enter your job details: ")
   print "Hi There!!! \nMy name is  %s,\nMy age is %d,\nI am located at %s and currently working as %s" %(name,age,location,job)

Further, I ran the program on the Python shell and obtained my first output for the same.

   >>>  RESTART:C:/Users/Desktop/nameagelocation.py 
   Enter your name: "Suzaane"
   Enter a two digit number as age: 37
   Enter your current location: "Buffalo"
   Enter your job details: "Research Programmer"
   Hi There!!! 
   My name is  Suzaane,
   My age is 37,
   I am located at Buffalo and currently working as Research Programmer
   >>>

There you go, you just wrote your first Python program and ran it on the Python interpreter.


Python Programming - Data Types

Chapter 3. Dataypes

[edit | edit source]

Python supports object oriented programming paradigm. This essentially means that Python programming paradigm is centered on data for solving all problems posed. A variable is location in the memory of the computer you are running the program. The assignment operator,=, is used to assign values to the variable. For e.g., x=5

Python allows for multiple assignments in a single command.

   >>> x,y,z=5,6,34
   >>> x
   5
   >>> y
   6
   >>>z
   34
   >>> x=3
   >>> z=5
   >>> x,y,z
   (3, 6, 5)
   >>> a=b=c=78
   >>> a,b,c
   (78, 78, 78)
   >>> a=5
   >>> a,b,c
   (5, 78, 78)
   >>>

3.1. Built-in Datatypes

[edit | edit source]

Python does not type cast variables. There is no need to instantiate variables before their usage quite unlike its C or Java counterpart. Python reduces the coding efforts on the programmer. Python provides three basic built data types namely None, Numeric class, and Boolean class.

3.1.1. None

[edit | edit source]

The word None denotes an object with no value.

3.1.2. Numeric class

[edit | edit source]

Python supports four different numerical types:

  1. int(signed integers)
  2. long integers that can be represented in octal and hexadecimal
  3. float – floating point real values
  4. complex – complex numbers

Out of the above mentioned four numeric classes, the Python numeric classes that implement integer and floating data types called int and float. The standard arithmetic operations of addition, subtraction, multiplication, division, and power of exponentiation can be used within parentheses forcing the order of operations from the normal operator precedence. There are two more very useful operations the remainder operator %, and integer division, //. When two integers are divided, the result is a floating point. The remainder operator % returns the remainder remaining after the division, and the integer division // returns the integer portion of a division after truncating the quotient.

   >>> 2*3
   6
   >>> x=2
   >>> y=3
   >>> x*y
   6
   >>> mystr="str"
   >>> mystr*x
   'strstr'
   >>> mystr*x*y
   'strstrstrstrstrstr'
   >>> print(5+3*4)
   17
   >>> print((5+3)*4)
   32
   >>> print(5**10)
   9765625
   >>> print(5/3)
   1
   >>> print(4/3)
   1
   >>> print(4//3)
   1
   >>> print(6%3)
   0
   >>> print(3/6)
   0
   >>> print(6//6)
   1
   >>> print(8%6)
   2
   >>> print(9**100)
   265613988875874769338781322035779626829233452653394495974574961739092490901302182994384699044001
   >>> print(float(5)+3*4)
   17.0
   >>> print((float(5)+3)*4)
   32.0
   >>> print(float(5)**10)
   9765625.0
   >>> print(float(5)/3)
   1.66666666667
   >>> print(float(4)/3)
   1.33333333333
   >>> 
   >>> print(float(4)//3)
   1.0
   >>> print(float(6)%3)
   0.0
   >>> print(float(3)/6)
   0.5
   >>> print(float(6)//6)
   1.0
   >>> print(float(8)%6)
   2.0
   >>> print(float(5)**10)
   9765625.0

3.1.3. Boolean class

[edit | edit source]

The boolean data type is implemented in the Python bool class representing the truth values. The possible state values for a Boolean object are True and False with the standard boolean operators, and, or, and not.

   >>> True
   True
   >>> False
   False
   >>> True==False
   False
   >>> False==False
   True
   >>> not True
   False
   >>> not False
   True
   >>> True and True
   True
   >>> True and False
   False
   >>> False and True
   False
   >>> False and False
   False
   >>> not not True
   True
   >>> not True and not False
   False
   >>>

3.2. Sequences

[edit | edit source]

Python is strongly typed, that is Python does not convert data from one type into another data type automatically. So if you have a string variable and a numeric variable, Python print command will throw an error instead of automatically converting one of them into another type and then print.

   >>> a=1
   >>> b="str"
   >>> b="this is a string"
   >>> print a + b
   Traceback (most recent call last):
     File "<pyshell#14>", line 1, in <module>
       print a +b
   TypeError: unsupported operand type(s) for +: 'int' and 'str'
   >>> print str(a)+b
   1this is a string
   >>>
   >>> print (a,b)
   (1, 'this is a string')
   >>> print a,b
   1 this is a string

3.2.1. String

[edit | edit source]

Python has a built in string class named “str”, so because careful while using a variable called str for your programming purposes. String is a series of Unicode characters. Strings can be enclosed within single quotes or double quotes. Multiple line strings can be denoted using triple single ‘’’ or double quotes “””.

   >>> mystring="This is a valid string"
   >>> type(mystring)
   <type 'str'>

Python strings are immutable, that is they cannot be changed after they are created. New strings can be created as we go on programming. Characters in the string can be accessed by the [] operator but cannot change the value. Strings are indexed with 0 at the beginning.

   >>> mystring="this is my string"
   >>> len(mystring)
   17
   >>> mystring[:]
   'this is my string'
   >>> mystring[0]
   't'
   >>> mystring[1]
   'h'
   >>> mystring[3:6]
   's i'
   >>>
t h i s i s m y s t r i n g
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
-17 -16 -15 -14 -13 -12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1
   >>> mystring[7:]
   ' my string'
   >>> mystring[6]="not"
   Traceback (most recent call last):
     File "<pyshell#61>", line 1, in <module>
       mystring[6]="not"
   TypeError: 'str' object does not support item assignment

3.2.2. List

[edit | edit source]

Lists in Python are one of the most used data types and is very flexible. The individual data items with the list may or may not be of the same type. Lists are declared by enclosing the data items in square brackets with each item separated from one another with a comma. The slice operator [] can be used to access the items with in lists. You can add items to the list, replace the items in the list, and delete items in the list using the index or using the item itself.

   >>> mylist=["file1", "my string", 5, 7]
   >>> print mylist
   ['file1', 'my string', 5, 7]
   >>> type(mylist)
   <type 'list'>
   >>> mylist[1]
   'my string'
   >>> mylist[0]
   'file1'
   >>> mylist[1:2]
   ['my string']
   >>> mylist[1:3]
   ['my string', 5]
   >>> mylist.append(10)
   >>> mylist
   ['file1', 'my string', 5, 7, 10]
   >>> mylist.append("python")
   >>> mylist.append("no this")
   >>> mylist
   ['file1', 'my string', 5, 7, 10, 'python', 'no this']
   >>> mylist[1:3]
   ['my string', 5]
   >>> mylist[4:]
   [10, 'python', 'no this']
   >>> mylist[-1]
   'no this'
   >>> print mylist
   ['file1', 'my string', 5, 7, 10, 'python', 'no this']
   >>> mylist[1]="new string"
   >>> print mylist
   ['file1', 'new string', 5, 7, 10, 'python', 'no this']
   >>> mylist[-1]
   'no this'
   >>> len(mylist)
   7
   >>> mylist[6]
   'no this'
   >>> print mylist
   ['file1', 'new string', 5, 7, 10, 'python', 'no this']
   >>> len(mylist)
   7
   >>> del mylist[6]
   >>> print mylist
   ['file1', 'new string', 5, 7, 10, 'python']
   >>> mylist.remove('python')
   >>> print mylist
   ['file1', 'new string', 5, 7, 10]

3.2.3. Tuples

[edit | edit source]

Tuples in Python are of immutable set or ordered items that can be strings, or any other type of variable. Once created, tuples cannot be changed.

   >>> x=(1)
   >>> print x
   1
   >>> px=(1,"my my")
   >>> print px
   (1, 'my my')
   >>> print px[1]
   my my
   >>> print px[1][1]
   y
   >>> px[1]="new string"
   Traceback (most recent call last):
     File "<pyshell#7>", line 1, in <module>
   px[1]="new string"
   TypeError: 'tuple' object does not support item assignment

3.2.4. Dictionary

[edit | edit source]

A dictionary in Python allows one to one mapping of data and key values. There is a key value that points to the value separated by a semicolon (:). Every key value is pair separated from each other with a common and the entire dictionary is enclosed in flower brackets. Keys must be unique values; however values may or may not be unique.

   >>> mydict={'a':"annual fees", 'b':'monthly fees', 'c':"biweekly", 'd':"weekly"}
   >>> mydict
   {'a': 'annual fees', 'c': 'biweekly', 'b': 'monthly fees', 'd': 'weekly'}
   >>> len(mydict)
   4
   >>> mydict['e']="daily"
   >>> mydict
   {'a': 'annual fees', 'c': 'biweekly', 'b': 'monthly fees', 'e': 'daily', 'd': 'weekly'}
   >>> mydict['e']="hourly"
   >>> mydict
   {'a': 'annual fees', 'c': 'biweekly', 'b': 'monthly fees', 'e': 'hourly', 'd': 'weekly'}
   >>>

3.3. Operators

[edit | edit source]

While working in Python, one must understand that Python calculates based on formulas. Values are bound to variables and then calculations are stored in the variables. There are operators which indicate a particular function being carried out on the values tied to variables and resulting in the output. Complex formulas can be built upon these simple operators that perform calculations and return values. In the following sections, we will examine Python operators.

3.3.1. Assignment Operators

[edit | edit source]

The simple assignment operator, =, assigns a numeric or Boolean value to the variable. The first assignment of the value to a variable creates the variable.

3.3.2. Relational and Logical Operators

[edit | edit source]

Relational and logical operators compare values on either side and return Boolean values indicating whether a test that was made using the relational and logical operator holds good or not. Table 1 provides introduces Python’s relational and logical operators.

Table 1 Python's relational and logical operator

Sl No. Relational Operator Description
1 == If the two values on the right hand side and left hand side of the operator are the same, the condition becomes true
2 != If the values on the right hand side and left hand side of the operator are not the same, the condition becomes true
3 < If the value on the left hand side is less than the right hand side of the operator, the condition becomes true
4 > If the value on the left hand side is greater than right hand side of the operator, the condition becomes true
5 <= When the value on the left hand side is less than or equal to the value on the right hand side, the condition returns true
6 >= When the value on the left hand side is greater than the value on the right hand side, the condition returns true
7 <> When the values on either side of the operator are not equal, then the conditional operator returns true
8 AND The statement checks for the Boolean value of the individual statements and returns the Boolean when both the conditions is true
9 OR The statement checks for the Boolean value of the individual statements and returns the Boolean when at least one of the conditions is true
10 NOT Returns the negative of the statement made

Python Working examples:

   x=4
   y=5
   print x==5
   False
   print x>y
   False
   print x>=y
   False
   print x<y
   True
   print x<=y
   True
   >>> x,y
   (5, 6)
   >>> (x<y and x<6)
   True
   >>> (x<y and x<1)
   False
   >>> (x>y and x<6)
   False
   >>> (x>y and x>6)
   False
   >>> not(x>y and x>6)
   True
   
   >>> (x<y or x<6)
   True
   >>> (x<y or x<1)
   True
   >>> (x>y or x<6)
   True
   >>>( x>y or x>6)
   False
   >>> not(x>y or x>6)
   True

3.3.3. Bitwise Operators

[edit | edit source]

Bitwise operators work on bits and perform bit by bit operation. In binary operations, numbers are treated as string of bits. For example, 0 is represented by 0, 1 is represented by 1, and 2 is represented by 10 in binary.

Sl No. Operators Functions
1 x << y Returns x with the bits shifted to the left by y places (and new bits on the right-hand-side are zeros). This is the same as multiplying x by 2**y
2 x >> y Returns x with the bits shifted to the right by y places. This is the same as //'ing x by 2**y
3 x & y Does a "bitwise and". Each bit of the output is 1 if the corresponding bit of x AND of y is 1, otherwise it's 0
4 y Does a "bitwise or". Each bit of the output is 0 if the corresponding bit of x AND of y is 0, otherwise it's 1
5 ~ x Returns the complement of x - the number you get by switching each 1 for a 0 and each 0 for a 1. This is the same as -x - 1
6 x ^ y Does a "bitwise exclusive or". Each bit of the output is the same as the corresponding bit in x if that bit in y is 0, and it's the complement of the bit in x if that bit in y is 1

Python program examples:

   >>> x=5 
   >>> x<<2
   20
   (Explanation: 5 in binary is 0101, moving left 2 times, and padding the right with zeroes, we have 010100 which is binary for 20)
   >>> x
   5
   >>> x>>2
   1
   (Explanation: 5 in binary is 0101, moving right 2 times, and padding the left with zeroes, we have 0001 which is binary for 1)
   >>> x=5
   >>> y=6
   >>> x&y
   4
   (Explanation: 5 in binary is 0101, and 6 in binary is 0110. “AND” ing each bit with its counterpart, we get answer 0100 which is binary for 4)
   >>> x|y
   7
   (Explanation: 5 in binary is 0101, and 6 in binary is 0110. “OR” ing each bit with its counterpart, we get answer 0111 which is binary for 7)
   >>> x^y
   3
   (Explanation: 5 in binary is 0101, and 6 in binary is 0110. Exclusive “OR” ing each bit with its counterpart, we get answer 0011 which is binary for 3)
   >>> x^y
   -6
   (Explanation: It's an artifact of two's complement integer representation.

In 16 bits, 1 is represented as 0000 0000 0000 0001. Inverted, you get 1111 1111 1111 1110, which is -2. Similarly, 15 is 0000 0000 0000 1111. Inverted, you get 1111 1111 1111 0000, which is -16. In general, ~n = -n – 1)

3.3.4. Membership Operators

[edit | edit source]

In Python, one can examine the existence of an item, element within a list, string, or a dictionary using the IN operator. The non existence of a particular pattern, element, value, key can also be verified by using the NOT IN operator. A programmer should always consider not naming the variables as key words used by Python.

   >>> a=["a",(1,2,3),"b", "python", 2.7]
   >>> "anu" in a
   False
   >>> "a" in a
   True
   >>> "anu" not in a
   True
   >>>
   >>> if "python" in a:

print "yay! Python exists"

   yay! Python exists
   >>>

3.3.5. Identity Operators

[edit | edit source]

The identity operators are used to compare two values and return a Boolean value as the result.

   >>> a=20
   >>> b=30
   >>> if a is b:

print "true! they are equal"

   >>> if a is not b:

print "true! they are not equal"

   true! they are not equal
   >>>

3.3.6. Operator Precedence

[edit | edit source]

The following table lists all operators from highest precedence to lowest.

Sl No. Operator Description
1 ** Exponentiation (raise to the power)
2 “~”, “ +”, “ –“ Complement, unary plus and minus (method names for the last two are +@ and -@)
3 * / % // Multiply, divide, modulo and floor division
4 + - Addition and subtraction
5 >> << Right and left bitwise shift
6 & Bitwise 'AND'
7 Bitwise exclusive `OR' and regular `OR'
8 <= < > >= Comparison operators
9 <> == != Equality operators
10 = %= /= //= -= += *= **= Assignment operators
11 “is”, “is not” Identity operators
12 “in”, “not in” Membership operators
13 “not”, “or”, “and” Logical operators


Python Programming - Control Structures

4. Control Structures

[edit | edit source]

A set of actions define the flow of events as decided by the flow chart. Within Python programming, none “None” values return True while variables with “None” values return False.

4.1. If statements

[edit | edit source]

The simplest control if statements return the value True when a condition is met. There is the simple one line if condition, followed by the if-else, and continued by the if-elif statements.

   >>> var = 100
   >>> if var==100:

print "yay! the variable is truly 100!!!"

   yay! the variable is truly 100!!!
   >>>
   >>> 
   >>> if (var==100): print "value is 100, its looks great!"
   value is 100, its looks great!
   >>>
   var = 100
   if var == 100:
       print "yay! the variable is truly 100"
   else:
       print "Nope! Better luck next time!!!!"
   >>>var=10
   >>> if var == 100:
           print "yay! the variable is truly 100"
       else:
           print "Nope! Better luck next time!!!!"
   Nope! Better luck next time!!!!

4.2. For Loops

[edit | edit source]

The “for” loops in Python executes a certain block of code for a known number of iterations. The specialty of “for” loop in Python is that the block of code can be iterated for the number of items existing within a list, dictionary, string variable, over a particular range of numbers in counted number of steps, and for the number of items existing in a tuple.

   >>> a=(10,20,30,40,50)
   >>> for b in a:
   print "square of " + str(b) + " is " +str(b*b)
   square of 10 is 100
   square of 20 is 400
   square of 30 is 900
   square of 40 is 1600
   square of 50 is 2500
   >>> c=["new", "string", "in", "python"]
   >>> for d in c:
           print "the iteration of string is %s" %d
   the iteration of string is new
   the iteration of string is string
   the iteration of string is in
   the iteration of string is python
   >>>
   >>> for i in range(10):

print "the value of "+str(i)+" is "+str(i)

   the value of 0 is 0
   the value of 1 is 1
   the value of 2 is 2
   the value of 3 is 3
   the value of 4 is 4
   the value of 5 is 5
   the value of 6 is 6
   the value of 7 is 7
   the value of 8 is 8
   the value of 9 is 9
   >>> a={'a':10,'b':20,'c':30}
   >>> for k in a:
       	print "the key is %s and the value is %d" %(k,a[k])
   the key is a and the value is 10
   the key is c and the value is 30
   the key is b and the value is 20

4.3. While Loop

[edit | edit source]

The while loop is executed till a conditional statement returns true. The conditional statement is evaluated every time before a block of code is executed, and the execution stops the moment the conditional statement returns false.

   >>> count = 0
   >>> while (count<9):
       print "the count is at iteration %d" %count
       count+=1
   the count is at iteration 0
   the count is at iteration 1
   the count is at iteration 2
   the count is at iteration 3
   the count is at iteration 4
   the count is at iteration 5
   the count is at iteration 6
   the count is at iteration 7
   the count is at iteration 8


Python Programming - Functions

5. Functions

[edit | edit source]

A function within Python is a set of code that performs a single utility and may or may not return a result. Functions provide methods of breaking up complex code into reusable blocks of code which can be used as building blocks of different programs. Python already provides for a lot of inbuilt functions such as print, input, etc. You can write your own Python functions called user defined functions.

5.1. Defining a function

[edit | edit source]

Like stated earlier, one can write a set of code to perform certain utility. The following rules provide a guideline for writing your own function. Functions are executed when they are called by their user defined function name.

Function blocks start with the keyword “def” followed by the user provided function name and parentheses (). The inputs that user provides to the function are placed within the parentheses, further extrapolating the parentheses can be used to define new parameters to be used within the user defined function. Python provides for documentation that be used to describe the function, author, date of creation, and the purpose of the user defined function, etc. The documentation of the user defined function can be accessed by using the __doc__ keyword after the user defined function name. The keyword return is used to exit the function, optionally passing an expression to the caller of the function.

5.2. Syntax

[edit | edit source]
   def functionname(parameters):
   ‘’’function docstring’’’

Code block

       	Return(expression)

Example

   >>> def squareofnum(n):
        This function returns the square of the number passed as the parameter
       return n*n
   >>> print squareofnum(3)
   9
   >>> print squareofnum.__doc__
       This function returns the square of the number passed as the parameter
   >>>
   >>> def myappendlist(mylist,a):
        this function appends a list to the already existing list
           mylist.append(a)
           return
   >>> a=[1,2,3,4]
   >>> b=[6]
   >>> 
   >>> a
   [1, 2, 3, 4]
   >>> b
   [6]
   >>> print myappendlist(a,b)
   None
   >>> a
   [1, 2, 3, 4, [6]]
   >>>

5.3. Function Arguments

[edit | edit source]

A function can be called by using passing the arguments in the right order, mentioning the keyword arguments, default arguments, variable length arguments.

   #function is defined here
   >>> def newfunction(n):
       print "inside function"
       answer= n*n*n
       return answer
   >>> print newfunction(2)
   inside function
   8
   >>> print newfunction()
   Traceback (most recent call last):
     File "<pyshell#203>", line 1, in <module>
       print newfunction()
   TypeError: newfunction() takes exactly 1 argument (0 given)
   >>>
   >>> def vistingcard(name, age="22"):
           print "the name is %s" %name
           print "the age is %d" %age
           return
   >>> vistingcard("new", 33)
   the name is new
   the age is 33
   >>> vistingcard(age=34, name="no name")
   the name is no name
   the age is 34
   >>> vistingcard(36, "newname")
   the name is 36
   Traceback (most recent call last):
     File "<pyshell#221>", line 1, in <module>
       vistingcard(36, "newname")
     File "<pyshell#218>", line 3, in vistingcard
       print "the age is %d" %age
   TypeError: %d format: a number is required, not str
   >>>

Variable length arguments can be passed to the function using the *. Example is provided below.

   >>> def variableargfunc(*argu):
       print "inside function"
       for a in argu:
           print a
           return
   >>> variableargfunc(10)
   inside function
   10
   >>> 
   >>> variableargfunc(10,20)
   inside function
   10
   20
   >>> 
   >>> variableargfunc([1,2,3,4,5])
   inside function
   [1, 2, 3, 4, 5]

5.4. Scope of variables

[edit | edit source]

There are two types of variables that are defined within the scope of the function that they are used. Variables within a function are local to the function and are called local variables with respect to the function and the global variables are defined outside the scope of the variables.

   >>> globalvariable=0
   >>> def scopefunc(n,m):
           globalvariable=n+m
           print "the local variable is %d " %globalvariable 
           return globalvariable
   >>> 
   >>> print "outside the function scope %d " %globalvariable
   outside the function scope 0 
   >>> scopefunc(5,6)
   the local variable is 11 
   11
   >>> print "outside the function scope %d " %globalvariable
   outside the function scope 0 
   >>>


Python Programming - Class and Objects

6. Classes and Objects

[edit | edit source]

Python uses object orientation since its inception owing to which fact creating classes, using classes and objects is absolutely easy.

6.1. Creating classes

[edit | edit source]

The class statement creates a new class definition. The user provided name for the class follows the keyword class followed by a colon as follows:

   class myclass:
   ‘The documentation of the class can be added here’
   Class objects
   Class methods
   class myclass:
       'This docstring provides for the details of the class defined'
       count=0
       def __init__(self,name,paycheck):
           self.name=name
           self.paycheck=paycheck
           myclass.count+=1
       def displayworkerCount(self):
           print "Total no of worker %d" %myclass.count
       
       def displayworkerName(self):
           print "Name of the user",self.name,"'s salary", self.paycheck
       
   >>> worker1=myclass("Nobody",15000)
   >>> worker2=myclass("SNGET", 10000)
   >>> worker3=myclass("Somebody", 20000)
   >>> worker4=myclass("Everybody",25000)
   >>> worker1.count
   4
   >>> worker1.displayworkerCount()
   Total no of worker 4
   >>> worker1.displayworkerName()
   Name of the user Nobody 's salary 15000
   >>> print myclass.__doc__
   This docstring provides for the details of the class defined
   >>>

The end user can check if the defined class has a particular method or object or instance defined within the class using the hasattr object.

   >>> worker1
   <__main__.myclass instance at 0x017D5990>
   >>> worker1.name
   'Nobody'
   >>> worker1.paycheck
   15000
   >>> hasattr(worker1,'age')
   False
   >>> hasattr(worker1,'displayworkerCount')
   True

The end user can add, modify, set, or delete the attributes of classes and objects at any time using the following methods.

   >>> worker5=myclass("","")
   >>> worker5.name
   ''
   >>> worker5.paycheck
   ''
   >>> worker5.name="New Body"
   >>> worker5.paycheck=50000
   >>>
   >>> worker5.name
   'New Body' 
   >>> worker5.paycheck
   50000
   >>> worker1.paycheck
   15000
   >>> worker1.paycheck=55000
   >>> worker1.paycheck
   55000
   >>> setattr(worker1, "paycheck", 60000)
   >>> worker1.paycheck
   60000
   >>> >>>
   >>> delattr(worker1, "name")
   >>> worker1
   <__main__.myclass instance at 0x0222EA80>
   >>> worker1.name
   Traceback (most recent call last):
     File "<pyshell#372>", line 1, in <module>
       worker1.name
   AttributeError: myclass instance has no attribute 'name'

6.2. Class Built-In Attributes

[edit | edit source]

By default, all Python classes have the following built-in attributes that can be accessed using the dot operator just like the __doc__ attribute that provides the documentation of the class.

  1. __dict__ : The dictionary of the namespace of the class
  2. __doc__ : Class documentation string or none, if undefined
  3. __name__ : Class name
  4. __module__ : Module name in which the class is defined. This attribute is "__main__" in interactive mode
  5. __bases__ : A possibly empty tuple containing the base classes, in the order of their occurrence in the base class list.

Trying the above methods for the above defined myclass, we have the following result.

   >>> print "The name of the class is :", myclass.__name__
   The name of the class is : myclass
   >>> print "The name of the module is :", myclass.__module__
   The name of the module is : __main__
   >>> print "The bases for the class myclass is :", myclass.__bases__
   The bases for the class myclass is : ()
   >>> print "The dictionary of namespace for myclass are :",myclass.__dict__
   The dictionary of namespace for myclass are : {'count': 4, '__module__': '__main__', 'displayworkerCount': <function
   displayworkerCount at 0x02244B70>, 'displayworkerName': <function displayworkerName at 0x02244BB0>, '__doc__': 'This
   docstring provides for the details of the class defined', '__init__': <function __init__ at 0x02244B30>}
   >>> print "The document string for myclass is: ",myclass.__doc__
   The document string for myclass is:  This docstring provides for the details of the class defined
   >>>


Python Programming - Handling Files

7. Files

[edit | edit source]

Python provides for more input and output functions. The simplest method of producing output is using the “print” statement.

There are two methods in which the Python interpreter reads the input provided at the terminal namely:

  1. raw_input

This command reads whatever is at the terminal as the input regardless of whether it is an expression or not and returns a string.

  1. Input

The input command evaluates the expressions as regular Python expressions and takes it as input.

The following examples highlight the differences between raw_input and input.

   >>> a=raw_input("enter your test here : ")
   enter your test here : new
   >>> a
   'new'
   >>> print a
   new
   >>> b=raw_input("enter your python expression :")
   enter your python expression : (1,2,3)
   >>> print a
   new
   >>> print b
   (1,2,3)
   >>> c=input("enter your text here :")
   enter your text here :"sunami"
   >>> print c
   sunami
   >>> d=input("enter your text here :")
   enter your text here :(1,2,3)
   >>> print d
   (1, 2, 3)
   >>> print type(d)
   <type 'tuple'>
   >>>e=input("enter your text here :")
   enter your text here :[x*x for x in range(5)]
   >>> print e
   [0, 1, 4, 9, 16]
   >>> f=raw_input("enter your python expression :")
   enter your python expression :[x*x for x in range(5)]
   >>> print f
   [x*x for x in range(5)]
   >>>

7.1. Opening and Closing Files

[edit | edit source]

Till now, we were writing at the input terminal and obtaining output at the terminal. Let’s move further to reading and writing files. Python provides for a plethora of functions to read and write files that may be text, or data files. File manipulation commands such done using a file object.

A list of couple of functions for operations on files are highlighted as examples within explanation provided with the comments. A file can be opened for reading, writing, appending existing text.

The “open” function opens a file that can used to read, write, or append data. For performing any of the above mentioned functions, every file must be opened first.

   >>> myfile=open("example.txt", "w")
   >>> myfile.write("Oh my god!! I just opened a new file ! \n")
   >>> myfile.write("I typed in a whole lot of text \n")
   >>> myfile.write("Thank god, its ending ! \n")
   >>> myfile.close()
   >>>

Please remember to close the file and then check if the actual file has the contents written into the file. Now, let’s go ahead and read the contents of the file that was just written.

   >>> myfile=open("example.txt", "r")
   >>> for a in myfile.readlines():
           print a
   Oh my god!! I just opened a new file ! 
   I typed in a whole lot of text 
   Thank god, its ending ! 
   >>>
   >>> myfile.close()
   >>> myfile=open("example.txt", "w")
   >>> myfile.write("Start of a new chapter ! \n")
   >>> myfile.write("The second line in charter! \n")
   >>> myfile.close()
   >>> myfile=open("example.txt", "a")
   >>> myfile.write("Oh my god!! I just opened a new file ! \n")
   >>> myfile.write("I typed in a whole lot of text \n")
   >>> myfile.write("Thank god, its ending ! \n")
   >>> myfile.close()
   >>> myfile=open("example.txt", "r")
   >>> print myfile
   <open file 'example.txt', mode 'r' at 0x02115180>
   >>> myfile.close()

There is a Python module “os” that provides methods to perform file-processing operations such as renaming and deleting files. To get the current working directory, do the following.

   >>> import os
   >>> print os.getcwd()
   C:\Users\Desktop\Projects\Upwork
   I already have an existing file named example.txt which I will rename using the Python os utility functions.
   >>>os.rename("example.txt", "sample.txt")


Python Programming - Command Line Arguments

8. Command Line Arguments

[edit | edit source]

There is a module sys that needs to be imported to read the command line arguments from the Python interpreter.

Here’s an example.

   >>> import sys
   >>> print 'The number of arguments at command line are ', len(sys.argv)
   The number of arguments at command line are  1
   No.  0 Arugment  C:/Users/Desktop/Projects/Upwork/firstworkspace.py
   >>>C:\Users\Desktop\Projects\Upwork>python second.py
   The number of arguments at command line are  1
   And the arguments are Argument List: ['second.py']
   >>>C:\Users\ Desktop\Projects\Upwork>python second.py 1 2 3 4
   The number of arguments at command line are  5
   And the arguments are Argument List: ['second.py', '1', '2', '3', '4']
   >>> count=0
   for b in sys.argv:
       print 'No. ', count, 'Arugment ', b
       count+=1
   >>>C:\Users\Desktop\Projects\Upwork>python second.py 1 2 3 4
   The number of arguments at command line are  5
   No.  0 Arugment  second.py
   No.  0 Arugment  1
   No.  0 Arugment  2
   No.  0 Arugment  3
   No.  0 Arugment  4
   C:\Users\Desktop\Projects\Upwork>python second.py 1 2 3 4
   The number of arguments at command line are  5
   No.  0 Arugment  second.py
   No.  1 Arugment  1
   No.  2 Arugment  2
   No.  3 Arugment  3
   No.  4 Arugment  4
   C:\Users\Desktop\Projects\Upwork


Python Programming - Learning Resources

9. Python Learning Resources

[edit | edit source]

This guide is intended to serve as a primer to learn Python programming. Only the basics of Python programming are covered in this guide. One can always use a variety of resources available on the WWW to learn Python. At the end of this guide, you will be able to write simple Python programs, open, read, append files, and other utilities. In this Python learning Resource guide, I have tried to provide as much as information possible to learn Python on your own.

  1. The official Python website provides a comprehensive learning material that you can use to learn.
  2. Learn Python
  3. Learn Python the Hard Way
  4. Tutorialspoint on Python
  5. Google Developers material on Python
  6. The Python Guru
  7. The Python Tutor

9.1. Specific Python programming applications

[edit | edit source]

The following books provide a good reference for delving into Python for specific applications.

  • Think Python: How to Think Like a Computer Scientist - Think Python provides acquaints you to scenarios of computer science through Python language with plenty of exercises, very less clutter. A section towards the end of every chapter is devoted to debugging. GUI and Markov analysis are also covered.
  • Python Koans - Python Koans is an interactive tutorial that employs a test driven approach towards development of code. Assertion statements are also explained.
  • Effective Python - Another book aimed at explaining specific ways of writing Pythonic code with the aim of turning an amateur into an advanced programmer.
  • Pro Python - An advanced programming guide used by intermediate experienced programmers.
  • Expert Python Programming - An advanced programming manual covering advanced concepts like decorators, method resolution, using super() and meta programming and general best practices. Later chapters detail best practices such as writing documentation, test-driven development, version control, optimization and profiling.
  • A Guide to Python’s Magic Methods - A collection of blog posts by Rafe Kettler explaining the ‘magic methods’ in Python. Magic methods are surrounded by double underscores (i.e. __init__) and can make classes and objects behave in different and magical ways.
  • Fullstack Python - A complete comprehensive manual offering advice on how to set up a web server to designing the front end, you can find everything in Fullstack Python.

9.2. How to help

[edit | edit source]

Python is constantly evolving open source software which takes humongous amount of information from the end users to make complete sense of the information. So if you want to give back that has doled out entire programming software that is free to use and develop, feel free to reach out to the Python community here and find ways to develop the code.

The official Python website has a section called community that provides complete and exhaustive methods that an individual can contribute towards the constantly evolving Python community.


Python Programming - Acknowledgement

Acknowledgements

I would like to thank my professor Parameshwar P. Iyer who encouraged me to work entirely on my own, the Python Software Foundation that has worked extensively to promote the Python programming community, and the various chapters under its purview, Pyladies Bangalore for giving me the platform to hone my Python programming skills. There were a lot of online resources that I referred to while preparing this book. I want to thank each one of them for their material, and for the time that they devoted for developing the material.

The cover for this book was obtained from the Python official website. So I wish to thank the original creators/designers of the Python language.

Thanks everyone who has contributed either directly or indirectly in the writing of this book.