# Introduction to Python Programming/Printable version

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

# 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

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

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
* 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.
* Double-click the installer, Python-2.xxx.yyy.exe. The name will depend on the version of Python available when you read this.
* Make sure that you have the administrative rights on the machine that you are working on.
* Step through the installer program.
* Some of the features can be removed from the installation in case you do not have enough space on your hard disk.
* Python will be installed with all the proper files and extensions.
* 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:
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

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:

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:

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.
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
Welcome to the Python party! Lets Python like we have never Python”ed before.

### 2.3. Kick starting with Python

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
To write multiple lines, just add ‘\n’ character where you want to introduce the new line. Just follow the following example.

### 2.3.1. Printing variables

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,
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.
Before printing integer variables, they have to be converted to string type using the str when printing along with string variables.

#### 2.3.2. Getting text inputs

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.
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.
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.
Further, I ran the program on the Python shell and obtained my first output for the same.
There you go, you just wrote your first Python program and ran it on the Python interpreter.

# Python Programming - Data Types
## Chapter 3. Dataypes

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.

### 3.1. Built-in Datatypes

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

The word None denotes an object with no value.

#### 3.1.2. Numeric class

Python supports four different numerical types:
* int(signed integers)
* long integers that can be represented in octal and hexadecimal
* float – floating point real values
* 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.

#### 3.1.3. Boolean class

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.

### 3.2. Sequences

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.

#### 3.2.1. String

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 “””.
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.
| 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 |

#### 3.2.2. List

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.

#### 3.2.3. Tuples

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.

#### 3.2.4. Dictionary

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.

### 3.3. Operators

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

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

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:

#### 3.3.3. Bitwise Operators

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

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.
print "yay! Python exists"

#### 3.3.5. Identity Operators

The identity operators are used to compare two values and return a Boolean value as the result.
print "true! they are equal"
print "true! they are not equal"

#### 3.3.6. Operator Precedence

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

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

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.
print "yay! the variable is truly 100!!!"

### 4.2. For Loops

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.
print "the value of "+str(i)+" is "+str(i)

### 4.3. While Loop

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.

# Python Programming - Functions
## 5. Functions

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

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

Code block
Example

### 5.3. Function Arguments

A function can be called by using passing the arguments in the right order, mentioning the keyword arguments, default arguments, variable length arguments.
Variable length arguments can be passed to the function using the *. Example is provided below.

### 5.4. Scope of variables

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.

# Python Programming - Class and Objects
## 6. Classes and Objects

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

### 6.1. Creating classes

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:
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.
The end user can add, modify, set, or delete the attributes of classes and objects at any time using the following methods.

### 6.2. Class Built-In Attributes

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.
* __dict__ : The dictionary of the namespace of the class
* __doc__ : Class documentation string or none, if undefined
* __name__ : Class name
* __module__ : Module name in which the class is defined. This attribute is "__main__" in interactive mode
* __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.

# Python Programming - Handling Files
## 7. Files

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:
* 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.
* 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.

### 7.1. Opening and Closing Files

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

# Python Programming - Command Line Arguments
## 8. Command Line Arguments

There is a module sys that needs to be imported to read the command line arguments from the Python interpreter.
Here’s an example.

# Python Programming - Learning Resources
## 9. Python Learning Resources

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.
* The official Python website provides a comprehensive learning material that you can use to learn.
* Learn Python
* Learn Python the Hard Way
* Tutorialspoint on Python
* Google Developers material on Python
* The Python Guru
* The Python Tutor

### 9.1. Specific Python programming applications

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

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.