+27833657551     admin@starscientist.org
    +27833657551     admin@starscientist.org

Introduction to Python

Python for beginners

In this python for beginners lesson, I will walk you through a series of examples script to get you started. By the end of this lesson, you will be able to write complex python codes.

What is Python

Python is an interpreted programming language. This makes it very portable and easy to debug but also slower than compiled languages. Python is very popular and has wide ranges of applications including but not limited to:

  software development
  web development
  data science
  mathematics, physics, astronomy

Astronomy Python Tools:

Python is widely used in Astronomy. Below you find lists of useful astronomy python packages:

   Astropy, a community-developed open-source package dedicated to astronomy
   APLpy, a plotting library based on Matplotlib to produce publication-quality plots of astronomical data.
   Spectral-cube, a python package to easily access and manipulate FITS cubes
   Kapteyn, provides many useful modules to deal with FITS files.
   Galpy, a python package dedicated to galaxy dynamics
   AstroML, a python module for data mining and machine learning for astronomy
   Pvextractor, produce a position-velocity diagram for a given slice
   Also check github.com/radio-astro-tools for different python modules relevant to radio astronomy
   Photometrypipeline (PP), uses Source Extractor and SCAMP for photometry analysis
   Photutils, open-source package to perform aperture photometry.

How to install Python

Python usually comes pre-installed on Unix or Linux distributions. Most additional packages can be easily installed using conda if you use the Anaconda installer or using pip:

conda install e.g., conda install numpy
pip install e.g., pip install numpy

To install a specific version of python, go to https://www.python.org/downloads/, choose your favorite version and download. Extract the tarball and install it. E.g.,

tar -xvf Python-3.6.9.tgz
cd Python-3.6.9/
./configure
make
make test
sudo make install

You may already have older versions of python3 or python2 pre-installed on your machine, to check the newly installed python, open your terminal and type:

which python3.6

Running the above command will give you an output like /usr/bin/python3.6

To check the exact python version you have type:

python3 -V 

This will output e.g., Python 3.6.9. To avoid potential clashes with previously installed python packages, install subsequent python packages using a virtual environment. First, install the most recent pip version using the below procedure because a simple sudo apt install pip might give you an old pip version. 

sudo apt install curl
curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py
sudo apt-get install python3.6-distutils
sudo python3.6 get-pip.py pip==19.2.3

Then, install virtualenv by:

sudo pip install virtualenv

After that, create a virtual environment. We will use python3.6 as our default python interpreter for our virtual environment.

virtualenv -p /usr/local/bin/python3.6 virtualenv-py3

Note that you can replace the name virtualenv-py3 above with any name you like. Now activate the newly created virtual environment:

source virtualenv-py3/bin/activate

After activating the virtual environment, your terminal will look like:

(virtualenv-py3) username@computername:~$

Finally, you can install any packages you like in your virtual environment using pip or conda. E.g., to install numpy, you would type:  pip install numpy. To exit a virtual environment, simply type:

deactivate

Getting started with python

We will start by running a series of small python scripts for this python for beginners' guide. The code will gradually become more complex as we proceed towards more advanced concepts. Python is an interpreted language and thus the code is executed line by line. This makes Python interactive and one can use the Python interpreter to run the code line by line. To run the Python interpreter, go to the terminal and type Python.

$ python
  Python 3.7.4 (default, Sep 22 2019, 20:51:12)
  [GCC 5.4.0 20160609] on linux
  Type "help", "copyright", "credits" or "license" for more information.
>>>

With the interpreter, you can execute lines of code piece by piece. From now on, we will use >>> to indicate that we are using the Python interpreter. For a more complex program, it is more convenient to write the script in a file. The file must have a ".py" extension to indicate that it is a Python script. To run a Python program, simply type python followed by the name of the file in the terminal console.

username@computername:~$ python program.py
>>> 2
2
>>> 2+3
5
>>> x=2
>>> y=3
>>> x+y
5

To exit the interpreter type quit(), Ctrl-D on Unix, or Ctrl-Z on Windows. You can also usee the following:

>>> import sys 
>>> sys.exit()

Consider the following script:

>>> x = 5
>>> y = x 
>>> x = 5 + 10  

In the above example, what do you think is the value of y? We will come back to this later but let's first explain the above statements. At line 1, we have x=5; this means that we assign a value 5 of type int into the variable x. Therefore, the variable x is of type int. Thus, the type of a variable is equal to the type of the object that it refers to. Let us verify this in the python interpreter using the type() class:

>>> x = 5
5
>>> type(x)
<type 'int'>

Note that when we assign an object into a variable, that variable points to the memory address of the object. We can use the built-in function id() to access the memory location of the object. E.g., At line 1 of the previous example, the variable x points to the memory location of the object 5. Let's see the memory address that the variable x points to:

>>> id(x)
43225336

Going back to our previous example, let's now see which value the variable y points to after changing the value of x.

>>> x = 5
>>> x
5
>>> y = x
>>> y
5
>>> x = 5 + 10
>>> x
50
>>> y
5

As you can see, y has the value 5 even after changing the value of x. This is because y is still pointing to the old memory address of the object that x was assigned to at line number 1. Let's verify this by checking the memory address that y is pointing to :

>>> x=5
>>>x
5
>>> id(x)
43225336
>>> y=x
>>> y
5
>>> id(y)
43225336
>>> x = 5+10
>>> x
50
>>> id(x)
43225096
>>> y
5
>>> id(y)
43225336

Identifiers/Variables

Python identifiers are names used to identify something such as class, functions, variables, values, etc. A python variable is a name given to the memory address that holds the value of an object. In our example, x = 5, x is a variable that stores the memory address of the value 5. A variable can be changed over time. Note that variables are identifiers but identifiers may not necessarily be variables. Identifiers/variables name must obey the following rules:

  Must begin with the alphabet letter (in uppercase or lowercase), or the underscore character '_'
  Cannot contain reserved keywords, blank spaces or special characters except the underscore '_'
  Variable names are case sensitive (e.g., Msun and msun are different variables)

The following reserved keywords cannot be used as identifiers/variable names.

anddelfromNoneTrue
aselifglobalnonlocaltry
assertelseifnotwhile
brefexceptimportorwith
classfalseinpassyield
continuefinallyisraise
defforlambdareturn

If you break the above rules, python will issue an error:

>>> with = 6
  File "<stdin>", line 1
    with = 6
         ^
SyntaxError: invalid syntax
>>> c&=3
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'c' is not defined
>>> dog weight = 7  
  File "<stdin>", line 1
    dog weight = 7  
             ^
SyntaxError: invalid syntax
>>> 100pets = 100
  File "<stdin>", line 1
    100pets = 100
          ^
SyntaxError: invalid syntax

To check if a particular identifier belongs to the python reserved keywords, you can use the built-in method iskeyword() of the keyword module

>>> import keyword
>>> keyword.iskeyword('nonlocal')
True
>>> keyword.iskeyword('numtel')
False

As we can see, the name nonlocal is reserved and thus the result of keyword.iskeyword('nonlocal') is True. In contrast, the name numtel is not a reserved keyword and therefore the result of keyword.iskeyword('numtel') is False

We can also use the python help utility to get the list of available keywords in Python.

>>> help()
Welcome to Python 3.7's help utility!
If this is your first time using Python, you should definitely check out
the tutorial on the Internet at https://docs.python.org/3.7/tutorial/.
Enter the name of any module, keyword, or topic to get help on writing
Python programs and using Python modules.  To quit this help utility and
return to the interpreter, just type "quit".
To get a list of available modules, keywords, symbols, or topics, type
"modules", "keywords", "symbols", or "topics".  Each module also comes
with a one-line summary of what it does; to list the modules whose name
or summary contain a given string such as "spam", type "modules spam".
help> keywords
Here is a list of the Python keywords.  Enter any keyword to get more help.
False              class               from             or
None               continue         global          pass
True                 def                 if                  raise
and                  del                 import          return
as                    elif                  in                 try
assert              else                is                 while
async               except           lambda        with
await                finally             nonlocal      yield
break                for                 not                 
help>

The type of variables does not need to be declared in Python. However, variables must be initialized before they can be used.

>>> gal_name
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'gal_name' is not defined
>>> gal_name = 'NGC3198'
>>> gal_name
'NGC3198'

At line 1, python issued an error because we have not initialized the variable name gal_name yet. To use the variable, we need to initialize it by assigning an object of a certain type to it. Python has a number of data types that a variable can be assigned to. We will see the different Python data types in the next section. We can assign values to variables using the general expression <variable-name> = <expression>.

>>> x = 10
>>> y = 3
>>> z = 5 + x * (1 - y)
>>> z
-15

When we change the value of variables multiple times, the value from the most recent assignment is retained.

>>> x = 10
>>> x
10
>>> x = x + 5
>>> x
15
>>> x = 'galaxy'
>>> x 
'galaxy'

We can assign the same object to different variables:

>>> a = b = c = d = e = 10

a, b, c, d and now has the same value, which is 10. We will come back to this later when we talk about list. We can also assign different variables to different values in a single line

a, b, c, d, e = 2, 10, 4, 5, 9

In the above case, a = 2, b =1 0, c = 4, d = 5, and e = 9. We will also come back to this when we talk about the tuple data type. A variable can be deleted using the syntax del <name-of-variable>.

>>> x = 5
>>> x
5
>>> del x
>>> x
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'x' is not defined