Python

How to Use Python

This article gives an introduction to Python; starting with a brief history, it discusses the factors driving Python’s adoption growth. We discuss how to install and run programs. We then discuss and run a small example program that fetches stock prices from the web and processes them.

1. A brief history of Python

Guido van Rossum created Python, an interpreted high-level programming language, and released the first version in 1991. The name was not borrowed from the commonly known family of the snake species. As per the official documentation, “when he began implementing Python, Guido van Rossum was also reading the published scripts from ‘Monty Python’s Flying Circus, a BBC comedy series from the 1970s. Van Rossum thought he needed a name that was short, unique, and slightly mysterious, so he decided to call the language Python.”

2. Why do we use Python?

Tools help us solve a problem, that is, to fulfill our requirements in an efficient way. Python is a solid tool in a wide variety of domains. With it, we can create software applications, from text editors to games to web applications to solve specific business problems. The real boost to its usage came when a large variety of useful libraries started getting created using it. Scientific and financial computing professionals came to the language for these libraries. They were attracted by its syntax and conciseness and it reads almost like pseudo-code. Success builds on success. More and more libraries were written in Python and used, so much so that the field that was called data mining effortlessly traversed into data science with machine learning, deep learning, and artificial intelligence. There is no other programming language that has got equal traction on both the scientific computing and web application side.

In the latest PYPL index, Python stands at the top of all programming languages. In their latest rankings, both TIOBE and Redmonk Language Rankings show Python at the second position.

In Learning Python (LP), Mark Lutz writes: “The choice of development tools is sometimes based on unique constraints or personal preference. After teaching Python to roughly 260 groups and over 4,000 students during the last 16 years, I have seen some common themes emerge. The primary factors cited by Python users seem to be these:

Software quality
For many, Python’s focus on readability, coherence, and software quality in general sets it apart from other tools in the scripting world. Its code is designed to be readable, and hence reusable and maintainable—much more so than traditional scripting languages. The uniformity of its code makes it easy to understand, even if you did not write it. In addition, it has deep support for more advanced software reuse mechanisms, such as object-oriented (OO) and functional programming.

Developer productivity
Python boosts developer productivity many times beyond compiled or statically typed languages such as C, C++, and Java. Its code is typically one-third to one-fifth the size of equivalent C++ or Java code. That means there is less to type, less to debug, and less to maintain after the fact. Python programs also run immediately, without the lengthy compile and link steps required by some other tools, further boosting programmer speed.

Program portability
Most Python programs run unchanged on all major computer platforms. Porting Python code between Linux and Windows, for example, is usually just a matter of copying a script’s code between machines. Moreover, Python offers multiple options for coding portable graphical user interfaces, database access programs, web-based systems, and more. Even operating system interfaces, including program launches and directory processing, are as portable in Python as they can possibly be.

Support libraries
Python comes with a large collection of prebuilt and portable functionality, known as the standard library. This library supports an array of application-level programming tasks, from text pattern matching to network scripting. In addition, Python can be extended with both homegrown libraries and a vast collection of third-party application support software. Python’s third-party domain offers tools for website construction, numeric programming, serial port access, game development, and much more (see ahead for a sampling). The NumPy extension, for instance, has been described as a free and more powerful equivalent to the Matlab numeric programming system.

Component integration
Python scripts can easily communicate with other parts of an application, using a variety of integration mechanisms. Such integrations allow Python to be used as a product customization and extension tool. Today, Python code can invoke C and C++ libraries, can be called from C and C++ programs, can integrate with Java and .NET components, can communicate over frameworks such as COM and Silverlight, can interface with devices over serial ports, and can interact over networks with interfaces like SOAP, XML-RPC, and CORBA. It is not a standalone tool.

Enjoyment
Because of Python’s ease of use and built-in toolset, it can make the act of programming more pleasure than a chore. Although this may be an intangible benefit, its effect on productivity is an important asset.

Of these factors, the first two (quality and productivity) are probably the most compelling benefits to most Python users.”

3. Advantages and disadvantages

LP was published in 2013. All reasons from the book, cited in the previous section hold good even today. In addition, we have seen that Python has become one of the most preferred choices of learning programming in schools and colleges. Other advantages that Python offers are a large and supportive community and its increasing adoption in IoT.

Python has certain disadvantages. It is slower than compiled languages like C / C++ / Java. Its programs tend to have higher memory consumption. It lacks true multi-threading. Though there are a few Python mobile application development frameworks available, there is no great support and ecosystem to aid mobile application development.

4. Download and install Python

For Microsoft Windows users, the easiest way to download and install Python is from the Microsoft Store. Open the Store app on your computer, search for Python, select the latest version that shows up, and hit Install. That’s pretty much it.

The other way is to go to the Downloads page. Download and run the Python installer file. They are available for both Windows and Mac OS.

Python comes pre-installed on Mac OS and Linux, so you are good to go without any extra installation. Only if you want to use a different version than what is available, you have to do some extra work. For example, if you have Python 2.9 installed on your Ubuntu Linux system and you want to use Python 3.8, you need to run the following commands:

sudo add-apt-repository ppa:deadsnakes/ppa
sudo apt update
sudo apt install python3.8

To check Python 3.8 is installed, run the following command:

python3 --version

Now the command python will use Python2.x and python3 will use Python 3.8

5. Write a program

When introducing a language, it is a tradition, set by Brian Kernighan and Dennis Richie, to write a “Hello, World” program, one that prints the words, Hello, World on the command console. In Python, you don’t have to do more than adding parentheses before and after this string. Yes, print (“Hello World”) is a complete Python program that performs the exalted tradition.

But let’s go a bit further and run a program that does a lot more, with so much less. The following program saved as a file get_stock_price.py gets an Indian public sector company’s stock prices in the previous calendar month and prints the average closing price in that month.

from datetime import datetime
import calendar
from pandas_datareader.data import DataReader
 
now             = datetime.now()
prev_month      = 12 if now.month == 1 else now.month-1
prev_month_days = calendar.monthrange(now.year, prev_month)[1]
 
start_date = f"{now.year}-{prev_month:02d}-02"
end_date   = f"{now.year}-{prev_month:02d}-{prev_month_days}"
 
df = DataReader("GAIL.NS", 'yahoo', start_date, end_date)
print(f"{df['Close'].min():.2f}, {df['Close'].max():.2f}, {df['Close'].mean():.2f}")

Look at the power of Python. It reads like English and does the job in about ten lines, without causing you to fret on compilation or packing i.e., running multiple commands.

6. How to run a program in cmd

During the standard Python installation procedures, it is made available in the binary path of your computer. So you just have to type python and the file name at the command prompt. The following screenshot shows the command to run get_stock_price.py

how to use python - program in cmd
Running program in cmd

7. How to run a program in IDE

When you install it, you also get a development environment, which is an editor and a Python shell. This environment is called IDLE and the editor is good enough in the early Python learning phase for you to run small to medium size programs, typically stand-alone programs.

The following screenshot shows get_stock_price opened in the IDLE editor.

how to use python - idle editor
Program open in the IDLE editor

To run the program, you have to just hit F5 on your keyboard or navigate to the menu, click Run and click “Run Module“. IDLE will run the program in its shell as shown below:

A program run in IDLE shell

There are other advanced editors and IDEs like Spyder and PyCharm (community edition), both of which can be used free of cost. Once you open the program file in these IDEs, you just have to hit the F5 key or “Run” in the menu to run your program.

8. More articles

9. Download the Source Code

This was an example of how to use Python.

Download
You can download the full source code of this example here: How to use Python

Mahboob Hussain

Mahboob Hussain graduated in Engineering from NIT Nagpur, India and has an MBA from Webster University, USA. He has executed roles in various aspects of software development and technical governance. He started with FORTRAN and has programmed in a variety of languages in his career, the mainstay of which has been Java. He is an associate editor in our team and has his personal homepage at http://bit.ly/mahboob
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

2 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Ravi
Ravi
2 years ago

Thanks for valuable information about python

Sowmindra Rotti
Sowmindra Rotti
2 years ago

Great article as always from Mahboob.
Simple, straight to the point and also focusing on the big picture.
Great one for Python beginners

Back to top button