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.
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:
Python 3.6.0 (v3.6.0:41df79263a11, Dec 22 2016, 17:23:13)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
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.
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.
$ vi myscript.py
In this file, we enter a one-liner code to print something. To insert text in the file, press ‘ i ‘.
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:
- Exit with saving changes – Press ‘ Esc ‘ + ‘ : ‘ + ‘ x ‘ + ‘ ! ‘
- 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.
$ python3 myscript.py
That was it! Wasn’t it simple?
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.