Introduction to Python (Part I)

Python is a high-level, general-purpose, interpreted programming language. It can be used to do some different purpose: from managing large data, simple to complex calculations to very specific objectives by using the pre-written packages.

There are 2 most common used versions of Python: Python 2 (current version is 2.7) and Python 3 (current version is 3.5). The 2 versions are different in some syntax, which Python 2 is the stable version while Python 3 is the developing version.

I. Basics syntax

A python script can be invoked by the first line ‘#!/usr/bin/python’ similar to using Perl.

Running a python program: we will start with how to run a python program Helloworld.py as below:

#!/usr/bin/python

hello = 'Hello World!'

print hello

To run a program in python we use:

python Helloworld.py

screenshot-from-2016-11-17-12-40-25

Addition flags can be used to calibrate the running process, details can be found here. A useful flag is -i (interactive mode) which allows you to control the variable and running process.

Screenshot from 2016-11-17 12-51-54.png

Command locals() is used to give a dictionary of local variables. All of the variables with __ are python pre-defined variables. This mode helps to check the variables during your program.

Using as a calculator: Basic mathematics operation can be used in Python, for example:

screenshot-from-2016-11-17-13-35-08

For more complex calculations, a package named numpy is used to complete these task. A tutorial in using Python package will be presented later.

II. Using external commands

Python allows running external commands using either module: os and subprocess.

import os

os.system('ls -l')

or

from subprocess import call

call(['ls','-l'])

Nguyen Cong Nghia – IESAS

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s