We are living in an information age society. Every person needs to be able to manage the vast quantum of information to which we are exposed. We also have at our disposal computers which allow us to manage all this information. There was a time when a handwritten note was perfectly fine. This moved to a typewriter in which occasional manual corrections were acceptable. Today, we are very intolerant of spelling mistakes or manual corrections because we believe that any organisation which is sloppy with spellings may be sloppy with the other work as well. We do not need to know how many buttons a mouse has or how many columns Excel has. We need to use them effectively. We no longer need to be able to multiply rapidly in our head. The calculator will do it for us. We do not need to remember facts. Google will help us with that. The computer has helped free some of the capacity in the brain. Hence, we can now use it for learning to program! A skill as important today as the three R's: reading, writing and arithmetic. I have been using the term 'computers' very loosely so far. As we go through these articles, we will become more specific. Each of us already has an image of what a computer is and what it can do. Our goal is to expose all people, especially the non-programmers, to computer programming. We will follow a minimalist approach. More details can be easily located thanks to Google. But one needs to know what is to be searched. We will stay as far away from the hardware details as we possibly can. Just as arithmetic is learnt by solving lots of problems, we hope to introduce you to the programming concepts by making you solve lots of problems. We will start with small problems and expand upon them. The language we have selected is Python. It is an interpretive language, meaning that as soon as you enter a command, the Python interpreter will respond. The language is aesthetically very appealing. It has a clear and consistent structure and is object-oriented. (You need not understand these words at present.) It is widely used in numerous programming domains, including writing game programming logic, web applications, scientific programming, etc. It is especially useful in extending functionality of many existing applications by adding task specific programs. It is available on a wide range of operating systems, including Linux and Microsoft Windows. Python is installed by default on most Linux distros and Mac OSX. On Windows, it will need to be installed. So, without any further delay, let us explore what Python has to offer. Using it as a Calculator – Exploring NumbersIn a terminal window, enter python. You will see the following prompt of Python >>> You are expected to enter a command and the computer, or more precisely, the Python interpreter will respond. Here is a brief transcript of a dialog we want you to try. >>>99 99 >>>2+3 5 >>>2-3 -1 >>>2*3 6 >>>3/2.0 1.5 >>>2.0/2/2 ... I won't tell you. Try. Hint, it could be one of two values - either 0.5 or 2.0. Python will always be consistent. It is the people who get confused. So, when in doubt, use parentheses "(" ")" to make your intentions clear to yourself. Try playing with various combination of numbers - including try entering a letter instead as well. Keep doing it till you are pretty sure about the rules Python seems to follow. Hopefully, you will be convinced that the computer works with numbers pretty much the way you expect it to. Now you can comfortably use the computer and Python rather than a calculator. You would have guessed by now that: Addition is represented by '+' Subtraction is represented by '-' Multiplication is represented by '*' Division is represented by '/' Integer Division is represented by '//' If you guessed '//', it is amazing. Try experimenting with 3/2, 3/2.0, 3//2 etc. This is one instance where the behaviour of Python is not what we may expect. Python3 will give the same answer for 3/2 as for 3/2.0. That behaviour can be obtained in Python2 by adding the line: >>>from __future__ import division # There are two underscores before and after future. >>># This is a comment/information for people. Python interpreter ignores any characters on a line after a # Exponentiation is represented by **. So, try >>>2**3 >>>3 + 2**2.5 >>>2*2.5**2 >>>(2*2.5)**2 Calculators have RegistersWe may want to save intermediate results or just save some long values like π. It is obviously convenient. In a programming language, we call these 'registers' or variables by names - preferably, meaningful names so that we can understand what we intended. Unlike a calculator, it is unlikely that you will run out of variables while writing your programs! To get the volume of a cylinder of height 9 cm and radius 2 cm, we can follow the following steps: >>>pi = 3.141596 >>>radius=2 >>>area = pi*radius**2 >>>volume = area*9 >>>print 'Volume = ', volume The print option allows us to display the results in a more flexible manner than on a calculator. I need a Scientific CalculatorWe need to tell Python that we wish to use math library. We do so by >>> >>>sin(30) -0.98803162409286183 Not the answer I expected. I need help. >>>help('math') The sinusoidal functions work with radians and there is a function to convert degrees to radians. >>>sin(radians(30)) 0.49999999999999994 Rounding errors are expected. So, this is what we expected. In the early days of computers, a programmer had to write a program to calculate interest for a bank. And he did. But he made a small modification. Instead of rounding the interest calculation, he truncated it and deposited the fraction of a cent into his own account. He made a fair amount of money until another programmer had to make a change in that program and could not understand the complicated logic for the fraction. Needless to say, banks are a lot more careful these days about rounding issues. My Own FunctionsI need to know how much I still owe the bank after I have paid a number of EMI's. I know each month what I owe increases by an interest component and decreases by the instalment I have paid. I can repeatedly compute the revised principal amount. I need to write a block of statements which will define the function. There will also be a block of statements which need to be repeated. We need to be able to tell Python interpreter how to detect a block. In our normal usage, we may have a list of ingredients which make up a recipe. So, we often write it as “Following ingredients will be needed:” and then from the next line, we indent and list each ingredient on a new line. We know the list is over once the indentation changes back to normal. Python uses indentation to identify a block. This is a critical difference which does not appeal to many people familiar with programming. However, as one uses it, it seems so natural because any half-way decent programmer will indent his code anyway. A minor catch, a tab and 8 spaces may look the same but they are not as far as Python is concerned. We recommend that each indentation be 4 spaces and do not use tabs for indentation. The keyword 'def' is used to identify a function. Since we may need our function many times, we will write it in a file. For this purpose, any text editor will do. But, Python comes with 'idle', a nice little editor for 'lazy' programmers. So, here is the code written in financial_functions.py. def balance_loan(loan_amount, interest_rate, instalment, instalments_paid): """ This method accepts loan taken, the annual rate of interest, the instalment and the number of instalments paid and returns the balance loan remaining """ # initialise the instalment number instalment_no = 0 principal = loan_amount # keep repeating. We will stop when our goal is achieved while True: principal = principal + (interest_rate/(12*100.0))*principal - instalment instalment_no = instalment_no + 1 # Are we done? if instalment_no == instalments_paid: break return principal Any statement which needs a block, e.g. 'def', 'while', 'if', ends with a ':'. The parameters passed to a function are specified in parentheses. We can write a long comment or document a function by using a triple quote. A very useful recipe for writing a loop is to use 'while True'. This loop will never terminate unless we explicitly break the loop, which is what we have done by checking the if condition. Checking a condition uses a familiar keyword 'if'. The possible operators are: Equals == Not equal to != Greater than > Greater than or equal to >= Less than < Less than or equal to <= The only surprise is '=='. This is because we use '=' for assigning new values. Hence, a different operator is needed for checking equality. Let us now use this function. We give the command 'python', start the interpreter and import our functions. >>>from
financial_functions import * >>>dir() ['__builtins__', '__doc__',
'__name__', 'balance_loan']
>>>balance_loan(100000, 10.0, 4615, 6) # a Rs. 1 lac loan at 10% repayable in 2 years 76832.00641530905 >>>balance_loan(100000, 10., 1075, 24) # a Rs. 1 lac loan at 10% repayable in 15 years 93608.662120108755 >>>print ' %.2f ' % balance_loan(100000, 10., 1075, 24) 93608.66 As we can see, on a 15 year loan, the loan amount does not go down substantially after paying EMI's for two years. The last entry also shows that we can use the print statement to display only 2 decimal places. For the ImpatientThe site http://www.python.org and http://wiki.python.org/moin/BeginnersGuide/NonProgrammers are the place to start. I like the tutorial by Josh Cogilati at http://en.wikibooks.org/wiki/Non-Programmer%27s_Tutorial_for_Python/Contents The great utility of computers is that they can do much more than just calculate. That will have to wait for the next part.
|
Python For Friends >