Sunday, 3 January 2016

A basic Introduction

Welcome to the world of Python Programming.

Before we start anything on this topic, I would like to assume the following,

  1. You know about computer programs.
  2. You know about different form of languages.
  3. You know the basics of using a computer like using notepad to write something on it.
  4. Copy paste and save on Notepad etc.
  5. You know how to deal with the command prompt/shell.
However, if you don't know about computer programs, you can read the information in this post, Computer Programs. This post gives you an insight why a computer program exists and what its basic functionality is.

If you are a beginner and yet to know about forms of programming language, the following two articles are just right for you,


If you do not have any idea of Unix Shell/ Windows Powershell or Mac OS Command Line, I recommend you complete this crash course on Command Line, Command Line Crash Course.

At this point, I assume that you are aware of Computer Programming, High Level languages and Command Line.

Please don't prove my assumptions wrong. Because, they are the strong base you will be requiring throughout all the subsequent articles.

Now, I want to be very frank on my writing rules,
  • While writing any article, I assume that you are in front of me and you have asked me a question and I have to answer the question for you. Questions are generally marked bold while my answers to them are in plain text. That may be weird way of writing. But that's the best way I can explain things in minute details.
    For example, look at this article on data, Data. Once you go through it, you will definitely understand what I mean.
  • Sometimes articles are too long. No way, you have to bear with them.
  • Most of the articles will be having real code examples and the output.
  • Although you will see the output in the article, I recommend you to write them on a notepad, save it, compile and run it to see the results yourself rather than relying on me.
  • Practice makes a man perfect. So, practice every day. If you are stuck with anything, comments are welcome. I will try to reply on your comment as soon as possible.
  • I strongle suggest you use simple text editors like Notepad, Notepad++, Vi etc. Please do not use highly functional IDE's and plugins. They will surely bar you from seeing the errors.
  • Wherever necessary, there will  be a section named Source Code Distribution. This section will details about the source code discussed in the article. You can download the source code and can verify the same with your program. But it is not recommended to directly download and use it for your purposes. That will actually defeat the purpose of learning.
I think after reading all these, some people will surely go back and check some other website. If you are still reading this, 'Welcome reader, I thank you to be here' and we'll start our discussion on Python in the next article.

Introduction to Python

So, we know about computer programs, how does it work, why do we need them etc. We are also capable of using the shell and a simple text editor.

Let's start our journey with Python.

Python is a general purpose, high level programming language. Python has a clear syntax which improves the readability of the code and is good for beginners. Python is less verbose than other languages like C++, Java etc. So, less code, more work !!!

Python supports multiple paradigm including Object Oriented, Imperative and Functional. Python is an interpreted language.

Following are the areas python can be used for development,

  • GUI Development - Standard Desktop Application
  • Web Application
  • System Administration tasks
  • Automation scripts
  • Financial Calculations
  • Data Analysis
You might find the list with more items in it in other places but these are the most concerned parts for development.

Now, let's take a look at the history...

Python started its life as a successor of ABC LanguageGuido van Rossum started writing the implementation on his Christmas holiday. Here is what Guido van Rossum wrote in 1996 about the origin of python,

Over six years ago, in December 1989, I was looking for a "hobby" programming project that would keep me occupied during the week around Christmas. My office ... would be closed, but I had a home computer, and not much else on my hands. I decided to write an interpreter for the new scripting language I had been thinking about lately: a descendant of ABC that would appeal to Unix/C hackers. I chose Python as a working title for the project, being in a slightly irreverent mood (and a big fan of Monty Python's Flying Circus).

Courtesy: Wikipedia

The first release of python appeared on 1991 and subsequently, the following releases came into existence,

Python is distributed under Python Software Foundation License and is compatible with GNU Public License. So, we can use python freely.


Some major Implementations of Python

Jython

Jython is a python implementation on Java Platform. This is designed to be run on JVM and can use Java Classes in Python Programming Language. This comes under Python Software Foundation License (v2). Curious readers are encouraged to take a look on Jython Website.

CPython

The default source code interpreter for Python written in C. So, when using the defaults, you are using this Interpreter.

PyPy

The python interpreter written in Python for speed and efficiency. This is designed to be compatible with the original CPython interpreter. This comes under MIT License. Curious readers are encouraged to take a look on PyPy Website.

IronPython

The python implementation written in C#, targeted for .NET platform. This project is open source under Apache License V2.0. Curious readers are encouraged to take a look on IronPython Website.

So, you can use any of the implementations mentioned above. If you are not sure which one to use, simply use the default one. I will be detailing the installation and verification of Python Installation in my next post.

Python Installation

You might have covered the introduction and may be now in a thought of writing programs using python.

Well, you can write your program right away. No issues. But you cannot actually run the program.

So, what's the use of writing a program that actually does nothing ?
Well, don't worry, you will run programs written in python. Only thing you need to have is python interpreter.

So, how to get that ?
Well, you need to install python on your system. Next I am going to detail this step for each type of OS.

For Mac OS X
Good news for Mac OS X users, python actually comes pre-installed on your system. So, no need to download or install anything. Simply open your terminal and type python, you will find that python is already working.

For Unix
Most unix distributions also come with pre-installed python. So, most likely you don't have to download or install python on your system
You can verify if your system comes with python or not. For details, read the Verification section.
If you don't see python installed on your system, you can check this article, [Tutor] how to install python on unix machine if you don't have root

For Windows
  • Go to python website, https://www.python.org
  • Go to Download tab and download version 2.7.x. Do not download python 3.
  • It will download the installer.
  • Once download is complete, click the installer which starts the installation.
  • You will be asked if you want to install python for all users or for your user only. Choose as applicable for you.
  • Click next. It asks for installation directory. You can use the default directory or can change the location.
  • Click next
  • It will start the installation. Wait for some time to complete this step. You may get Security warning from Windows. Click Yes.
  • Once the installation is complete, click finish.
For Android
If you want to learn python on the go and write some useful stuffs on your Android device and use it later, well python has that capability too. You don't need your laptop or desktop to run python applications. Let me guide you,
  • Go to Play Store
  • Search for QPython
  • Install the application
  • Now you can use the console, write programs and run them on your android device as well
Let me take you to this application a little bit.

This is the first screen, slide right to the next window,


You can select what you want to do. I am choosing console and let's see how this looks,


You can see that this screen looks almost the same as a standard PC console. Type some python commands on it and the console returns the result.

Now, let's look at the editor window.


In this window, you can write your own python scripts, can save it, run it and other options you can explore.

In programs, you can view all the programs,

Tap on a program and it will show you the available commands for the file like run, edit, rename etc.

The qedit4web.py is a beautiful program which allows you to connect to QPython over wi-fi to a PC. Check it out.

Cool, right ?
How are you planning to use it ?

Verification
Once the installation is complete, open a terminal and type the following,
python

You should see similar to the following,
Python 2.7.11 (v2.7.11:6d1b6a68f775, Dec  5 2015, 20:32:19) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>

Congratulation, you have successfully installed python and it is ready to use.

Now let's do some simple calculations and greet people using python,
>>> 2+3
5
>>> 4*5
20
>>> 2/5
0
>>> 2.5/5
0.5
>>> 5+8
13
>>> print "hello"
hello
>>>exit()

Cool. right ?

But what about writing some programs ?
Well, we'll discuss that in our next articles. But for this time, we'll write short program that we can run on python.

Let's write this short program which greets the world,
print "Hello World"

Open a text editor, write this line and save it as hello_world.py

Now open terminal and change directory to the directory where you have saved the file and run the following command,
D:\Palash\python\trunk\src>python hello_world.py
Hello World

D:\Palash\python\trunk\src>

And you can see that your program greets the world.

SAME OLD HELLO WORLD.
Yeah, this way of greeting the whole world is very much common in use, how about actually greeting the user who is running the program ????

Interesting !!!

OK, let's write the following programming which asks the user to input his name...
person = raw_input('Enter your name: ')
print 'Hello', person

Now write these lines in a file and save it as hello_user.py and run the file using python command,
D:\Palash\python\trunk\src>python hello_user.py
Enter your name: Palash Kanti Kundu
Hello Palash Kanti Kundu

D:\Palash\python\trunk\src>

When you will run the program, the system will ask you to enter your name and wait until you enter your name. Once you have entered your name and hit return, you will see the output which actually greets you.

Let's run this program again,
D:\Palash\python\trunk\src>python hello_user.py
Enter your name: Suman Kundu
Hello Suman Kundu

D:\Palash\python\trunk\src>

Now you see, you get a different output based on the user input. Now let's run this program for some more time,
D:\Palash\python\trunk\src>python hello_user.py
Enter your name: Totan das Kundu
Hello Totan das Kundu


D:\Palash\python\trunk\src>python hello_user.py
Enter your name: Subhra Datta Roy
Hello Subhra Datta Roy
D:\Palash\python\trunk\src>python hello_user.py Enter your name: Radhika Kittur Hello Radhika Kittur D:\Palash\python\trunk\src>python hello_user.py Enter your name: Amrita Pattanaik Hello Amrita Pattanaik D:\Palash\python\trunk\src>python hello_user.py Enter your name: Annu Singh Hello Annu Singh D:\Palash\python\trunk\src>python hello_user.py Enter your name: ANY_NAME Hello ANY_NAME

That's it. You have successfully installed python, performed some mathematical calculations, greeted the world, greeted the user who is using the program.

Well, in our next sections, we'll be discussing the way you write python programs and its different syntax and all.

Have fun till then...

Source Code Distribution

The source codes associated with this articles can be downloaded from github,
Prev     Next

Python shell

Well, now I expect that you have set up your environment so that you can learn python on you own. May be you have run the hello_world.py or hello_user.py script and verified the output, may be you have changed something in the script and tried to run it again to experience a different output or you may have done nothing.

Whatever you have did, if you are here, then at least I can expect you can tun python on your system.

Python is good when you want to learn it. May be it looses some of the features of other languages, may be it has some extra features it adds to the set or may be it is similar to the other programming language you may have already used, we are not going into that. We are not here to judge any language rather we are here to learn new things that python can do for us.

And seriously one of the things I like the most about python is that it can work pretty perfect as a calculator. May be you are in hurry and you need to perform a very simple calculation or may be you need to just check what "58*7+98*765-9.5+80" looks like or may be in your program you have come with a condition and want to know what it actually evaluates to in the run-time, you don't have to do anything apart from opening a new terminal and typing python and finally typing your query.

That's all you have to do to perform very simple to very complex mathematical expression evaluation.

So, if you have python installed in your system, you don't need a calculator and the shell will work for you in the fastest way possible.

Enough description, now let's try with the example I started.

Open terminal and type python.

It will show up the details of the version and some other texts. Now simply key in mathematical expression and you will get the answer within a second. Let me actually show you how it looks like in the terminal,

Pretty cool right ?
Well, you can do more than this. In fact you need not write a program for learning the basics of the language.

Amazed ?
I was too.

What about standard mathematical functions ?
Can you use them ?

Well, yes, you can.

Let me show you some of them...
palash@ubuntu:~$ python
Python 2.7.6 (default, Jun 22 2015, 17:58:13) 
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import math
>>> math.log(2)
0.6931471805599453
>>> math.log10(10)
1.0
>>> math.log(15, 15)
1.0
>>> math.sin(math.pi)
1.2246467991473532e-16
>>> math.sin(0)
0.0
>>> math.sin(math.pi/2)
1.0
>>> math.cos(math.pi)
-1.0
>>> math.tan(math.pi/2)
1.633123935319537e+16
>>> math.tan(math.pi/4)
0.9999999999999999
>>> math.cos(90*math.pi/180)
6.123233995736766e-17
>>> math.ceil(4.32)
5.0
>>> math.floor(4.32)
4.0
>>> math.factorial(4)
24
>>> math.factorial(25)
15511210043330985984000000L
>>> math.factorial(90)
1485715964481761497309522733620825737885569961284688766942216863704985393094065876545992131370884059645617234469978112000000000000000000000L
>>> math.factorial(900)
67526802209645841583879061361800814224269427869589384312198268703685091643180416969132446952698303794226010370578672908593198347699886928591906501031587651846976759681112609524787093848004428636186893395272784450630354080243217646658024696659065951793757223520229235577548653833681102170973893746054649126415909143150172860721156685810655759230011450132992176454983227538696340112610447029002337004887877266387704586077293585433151612518800147764461182680822867092786694982831838641800997499819339206579415325649748486265233918911087114592440896594062675914294925816719862178374679272092637524786939036290035924271782253738059886933923447877769583003016705363339031413069155837518524761078342052635475632113169618774549275701480106933362990003732589370593557325299434734459295866728988740794174654391479926000848846686708729736713207285203712732201272410830836913052635365082888725171636081587151603468291106754640398232146673627370895934090777828827549554232436190464827998683927179246029919443251026464452337939599198528297828591122689960620361238248313158071643395848405047261412680039877733761849874447323867911712630023171745968278465780558568067035013885275080292137360491875164947724464221693533755035300065350065137490832039523382963747026185653050331832380991844842560750923543775188582096487476950254418365198999674684417286265442786651594404781622946901879166382930714196908227460133027605817864877377712193142137625430353718448269390732615776645283198828602917680224041088993892610506802195917247838900106910698057030379190571057605849323113308634452008179881165616449767648354161225066967961297609698742737923389391615207441152319392845687673311899247085327703421862972871644495409572259985563215471482083325653231777113271326579970310755604973969708949477374254974480294652427022436705380184064008853457214518515270985563195412993145274057688634448812449445800617631162768243125606424844709372022149908463572254912654907763445758543980999149122998104378965626781898655221443263601405152073199706585080288735040205417371277253096243200000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000L
>>> math.isinf(math.tan(math.pi/2))
False
>>> math.exp(2)
7.38905609893065
>>> math.pow(100,100000000000000000)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
OverflowError: math range error
>>> math.pow(100,100000000000)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
OverflowError: math range error
>>> math.pow(100,1000000)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
OverflowError: math range error
>>> math.pow(100,100)
1e+200
>>> math.sqrt(25)
5.0
>>> math.sqrt(25567)
159.89684174492004
>>> math.radians(30)
0.5235987755982988
>>> math.radians(90)
1.5707963267948966
>>> math.tan(math.radians(90))
1.633123935319537e+16
>>> 

Pretty cool !!!

Once you get the hang of it, you'll surely look for python to perform some calculations. If you look carefully, you'd find that, to perform calculations like changing degree to radian or vice versa or to calculate a factorial or to get logarithm of any base, you simply need no function or method to write. All these are built in and quite fast as well, you can find that I've also performed factorial of 900, which I got in less than a second and the result seems to be correct (although I have not verified it digit by digit).

However, if you are debugging your application and you want to know the result of some calculation, just open the shell and perform the calculation straightaway.

Pretty much useful I've found.

Question arises here, what is the first line,

palash@ubuntu:~$ python
Python 2.7.6 (default, Jun 22 2015, 17:58:13) 
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import math

Well, this is an import statement, which imports the standard math library of python. Without this library, we could not perform calculations which requires the library function (like math.cos, math.ceil, math.exp etc.)

Now, the question arises, we can do so many things in python shell, then can we write a whole program in it ?
Of course you can. Let me show you.
>>> def addTwoNumbers(a, b):
...  return a+b;
... 
>>> addTwoNumbers(4,3);
7
>>> 

So, we've defined our own function which takes two number input and returns the sum of these two numbers. After defining the function, we've simply called the function from shell with the input and this returns the result and prints it out in the shell itself.

So,  you can see that you can do almost everything in python shell. Although it is acceptable to write your whole code in the shell but it is not recommended practice. So, the better way to put your logic is in a file and run it in the shell.

Now, you may want to get out of the python shell and want to resume your console. If you want to do so, here is how you can do it,

>>> quit()
palash@Home-Computer ~ $ 

In our subsequent discussions, we'll look into the programming aspects and different coding blocks of python. Till that enjoy using python to perform calculations or pretty small stuffs.

Hello World!!!

If you are from a programming background, you already have assumed what is going to be in this segment and if you are not, let me tell you a basic truth, these two words have kicked trillions of neurons. It may seem just two words but it is more powerful than anything in any programming.

You will understand the reason very soon...

So, let's get our hands dirty with python.
  1. As usual, open your favourite terminal (Powershell, Console, KSH, Bash etc.).
  2. If you have Vi editor installed on your system, open it otherwise, check this post Vi Editor.
  3. You should provide a name like hello_world.py while opening the editor. Please check the post on Vi Editor to know more about it.
  4. Type the following line in the editor,
    print "Hello World!!!"
    
  5. Now save the file by pressing Esc + ZZ 
  6. The very next thing you are going to do is to run the program
  7. Once you are back in terminal, type the following,
    python hellow_world.py
    
  8. You are expected to see the following output in terminal,
    Hello World!!!
    
You are amazed at your creativity, right ???
Yes, you are creative and you want to take it to the next level and I am here to help you.

Now check the first paragraph of this article and realize why I said so about 'Hello World'.

So, you have printed some line on the terminal, but you are thinking, how can I print my name on it.
Right  ?

Well, just try around, may be you can get some idea on how to do it. I am leaving this as an readers' exercise.
The output should match with the following,
Hello Palash!!!

You know, Palash is my name, so you should change accordingly or it is good if you want to see your system greeting me !!!
:)





Well with greeting yourself with a message printed on terminal ?
Now, let's try something interactive.

What if, you have thrown your first program to your friends in school and they run it in their machine. May be they won't like it every time showing your name only. They may want to see their name as well.

So, what are you going to do ?
Well, you can do two things,
  1. Create one file for each of your friends and ask them to run their own file.
  2. You can ask your friend for his name in the program itself and you should take input of their name and print a greeting message.
Many of you are thinking of the first way, I know and it is good. It will give you lot of exposure to vi editor and also some typing experience which you'll cherish later. Try it out and come back once you are done (and bored, may be).







Done ???
Now, let's see how we deal with the same thing in the second way...

Open vi editor with a file name hello_user.py and paste the following lines in it,
person = raw_input('Enter your name: ')
print 'Hello', person, '!!!'

And try to run this file using python command, as follows,
python hello_user.py

Now let's see how it works,

With only a single program, you can amaze many of your friends.

Cool !!!
Isn't it.

Well, many of you might have thought, why the file extension is set as .py.

Well, you can give it any extension you want as long as the content is something that python understands or in that condition even you can omit the extension but as a convention, we love to give it .py extension.

Following is a snap from my system with different extension of same python program,

You should notice that, in each case the same output is shown. Still, we'll be using .py extension throughout the course and may be later on.

I've recorded all the screen-cast sessions to make it more convenient for you while going through this post. You can check out if you want.



Well, that was it, I know your curiosity level has grown and you want to do more. But before going any further, you must do other alternatives and also should come up with other variations of these two programs. Practice this very basic concept, get hands dirty on vi editor and python interpreter, the print statement. We'll come back with new concepts.