Friday, 13 January 2017

Python Interpreter: How to use

One of the most useful features in Python is its interpreter. In my view, it is what makes a Python so special as a language. With the Python interpreter, you can gain so much productivity as compared to using other languages such as C++ or C#.

For instance, if you are required to compute the following mathematically formula:


You would prefer to use a calculator rather than use C++, right?

If you really want to use C++, there are (seriously) quite a lot of steps needed such as:

  1. Create a new Visual Studio solution
  2. Create a C++ project using the Wizard
  3. Open the editor to start coding.
    • Include the correct header files (e.g. <cmath>, <iostream>)
    • Code the formula in C++ 
    • Print out the final result using std::cout, std::newline, etc
  4. Compile the codes
  5. If the compile fails, try to figure out where is the syntax error. Repeat Step 3.
  6. Run the executable
  7. If the final result is wrong, Repeat Step 3.

This is commonly known as the "edit-compile-run" cycle and it can takes quite a lot of effort compared to using a calculator.

How about Python? Well, you can actually think of the Python interpreter as a super-calculator. All you need to do is to type the following lines inside the interpreter:

>>> from math import cos, sqrt
>>> a=1
>>> b=2
>>> C=0.7
>>> print('Answer: ', sqrt(a*a+b*b-2*a*b*cos(C)))

Answer:  1.3930654151410284

This gives you the answer quickly.

What if you typed the wrong value for the variable b?

No sweat. Just type the correct value inside the interpreter and the old value will be changed instantly. There is no need to open up the editor at all.

Note that you can recall the previous line(s) inside the interpreter by pressing the "up-arrow" key.

By breaking away from the "edit-compile-run" cycle, you are able to accomplish your tasks faster. This means you save time and become more productive.

In the event that you have to reuse your tested code, you can save it into a script. Then you can copy-and-paste from the script into the interpreter whenever you need to run it again.

In my future posts, I would like to show you how to get help from the interpreter and how to write functions using the interpreter. That is, writing functions without using an editor. The intention is to break away from the "edit-compile-run" cycle so that you get better productivity.

No comments:

Post a Comment