Interactive and script mode programming

By | November 26, 2018

Python program can be run using interactive and script mode of programming. Let’s discuss about both in this blog.

Note: I’m using macOS and running python in Terminal app. 

Interactive mode

In interactive mode, we want to interact with python. How can we interact ?

Basically, we invoke python interpreter without passing the script file in parameter. It launches python prompt. 

To understand how it works, please see below:

You can launch python prompt like shown above, in your terminal. Start entering code, like we saw in our previous blog, in the prompt lines.

This is one of the most powerful feature of any programming language. That is to be interactive. I am a big fan of this feature. 

Especially, when you will be doing scientific programming, this feature of python will be so much useful.

Script mode

In script mode of programming, python interpreter is invoked with script parameter. That means, we run a python script file. 

Python script file has .py extension. So, we can write our code in a file with .py extension and run it through terminal.

Let’s write our first python script. Open the terminal and type following command.

For this example, we are using vim editor. You can write python scripts in any text editor. You just have to save the file with .py extension.

In this file, we enter a one-liner code to print something. To insert text in the file, press ‘ i ‘.

vim-python-code-programming-mode
vim-python-code

Programmers make jokes about quitting vim.  If you don’t know how to quit vim, then don’t be abashed by that. Each of us have struggled at some stage with it 😀 

So, there are two common ways to quit the vim:

  1. Exit with saving changes – Press ‘ Esc ‘ + ‘ : ‘ + ‘ x ‘ + ‘ ! ‘
  2. Exit without saving changes – Press ‘ Esc ‘ + ‘ : ‘ + ‘ q ‘ + ‘ ! ‘ 😉 😀

I have to share at least one with you.

Q: How do you generate a random string?
A: Put a Windows user in front of vi, and tell them to exit

To run the script, enter the following command into bash Terminal.

That was it! Wasn’t it simple? 

Summary

In this blog, we learnt about two different modes of programming in python. Both are very useful and have their own applications.

Interactive mode has helped me with scientific programming. I can execute my code line-by-line, check each data structure and visualise it as well using python libraries.

Script mode I prefer when my script has to deal with large chunks of data and runs for longer time. I experienced that execution is much faster.

One thought on “Interactive and script mode programming

  1. Pingback: Introduction to Python Programming - Harsh Thaker

Leave a Reply

Your email address will not be published. Required fields are marked *