First Programming Tutorial, that too in Python, yay!. If you are a beginner in programming, python is the language most people will suggest you to learn. Python code is simple, short and clear. It’s a perfect choice for novice programmers.

Consider this C-language code which adds two digits and displays the result.

#include <stdio.h>
int main(int argc, char*argv[])
{
    int n1,n2,n3;
    scanf("%d",&n1);
    scanf("%d",&n2);
    n3 = n1+n2;
    printf("%d\n",n3);
}

Now consider this Python code, which does the same.

import sys
a = sys.stdin.readline()
b = sys.stdin.readline()
c = int(a) + int(b)
print c

See the difference?

Python is great becasue:

  1. You will only need to write less lines of code compared to other languages for any given problem, hence it is more readable – thus greater productivity.
  2. It has a Beautiful syntax. It enforces code indentation, which is always a good programming practice for other languages too, don’t you agree?
  3. Python is Open Source and Free to use even for commercial applications.
  4. It’s Portable.
  5. It’s Object-Oriented but that is not enforced unlike Java.
  6. Python is FUN and Easy.

Python is a programming language that lets you work more quickly and integrate your systems more effectively.  Python runs on Windows, Linux/Unix, Mac OS X, and has been ported to the Java and .NET virtual machines. Python is free to use, even for commercial products, because of its OSI-approved open source license.  -python.org

There are currently two popular versions of Python 2.x and 3.x.  Most of the code you will encounter on the internet is for Python 2.x.  You can learn more about differences in both versions HERE.

For the purpose  of this tutorial, we we use Python 2.6 on Windows. You can download it from Python Download page.

After downloading the executable and installing it (default location is : C:\Python26), first we need to add Python to our PATH. For this we need to open command prompt and enter:

path=%path%;c:\Python26

After it’s done we can get our hands dirty with some coding.

Open notepad. Copy and Paste the below written code in it.

atomic_mass = {'Ru': 102.91, 'Pd': 106.4, 'Pt': 195.09, 'Ni': 58.71, 'Mg': 24.305, 'Na': 22.99, 'Nb': 92.906, 'Db': 268.0, 'Ne': 20.179, 'Li': 6.941, 'Pb': 207.2, 'Re': 128.207, 'Tl': 204.37, 'B': 10.81, 'Ra': 226.03, 'Rb': 85.468, 'Ti': 47.9, 'Rn': 222.0, 'Cd': 112.41, 'Po': 209.0, 'Ta': 180.95, 'Be': 9.0122, 'Fr': 223.0, 'Te': 127.6, 'Ba': 137.33, 'Os': 190.2, 'La': 138.9, 'Bh': 272.0, 'Ge': 72.59, 'Zr': 91.224, 'Tc': 97.0, 'Fe': 55.847, 'Br': 79.904, 'Sr': 87.62, 'Hf': 178.49, 'Hg': 200.59, 'He': 4.0026, 'C': 12.011, 'Cl': 35.453, 'Rf': 265.0, 'P': 30.974, 'F': 18.998, 'I': 126.9, 'H': 1.0079, 'Mo': 95.94, 'v': 50.941, 'Ac': 227.0, 'O': 15.999, 'N': 14.007, 'Kr': 83.8, 'Si': 28.086, 'Sn': 118.69, 'W': 183.84, 'Y': 88.906, 'Sb': 121.75, 'Bi': 206.98, 'Al': 26.982, 'Sg': 271.0, 'Se': 78.96, 'Sc': 44.955912, 'Zn': 65.38, 'Co': 58.933, 'Ag': 107.87, 'Mt': 276.0, 'k': 39.096, 'Ir': 192.22, 'S': 32.06, 'Xe': 131.3, 'Mn': 54.938, 'As': 74.922, 'Ar': 39.948, 'Au': 196.97, 'At': 210.0, 'Ga': 69.72, 'Hs': 227.0, 'Cs': 132.91, 'Cr': 51.996, 'Ca': 40.08, 'Cu': 63.546, 'In': 114.82 }

invatomicmass = dict((v,k) for k, v in atomic_mass.iteritems())

symbols = {'krypton': 'Kr', 'copper': 'Cu', 'rubidium': 'Rb', 'iodine': 'I', 'rhenium': 'Re', 'gold': 'Au', 'radium': 'Ra', 'neon': 'Ne', 'oxygen': 'O', 'cobalt': 'Co', 'germanium': 'Ge', 'titanium': 'Ti', 'technetium': 'Tc', 'zinc': 'Zn', 'astatine': 'At', 'arsenic': 'As', 'radon': 'Rn', 'hydrogen': 'H', 'fluorine': 'F', 'polonium': 'Po', 'platinum': 'Pt', 'silicon': 'Si', 'hafnium': 'Hf', 'meitnerium': 'Mt', 'lead': 'Pb', 'sodium': 'Na', 'thallium': 'Tl', 'chromium': 'Cr', 'selenium': 'Se', 'iridium': 'Ir', 'seaborgium': 'Sg', 'ruthenium': 'Ru', 'tin': 'Sn', 'actinium': 'Ac', 'chlorine': 'Cl', 'osmium': 'Os', 'sulfur': 'S', 'tungsten': 'W', 'lithium': 'Li', 'hassium': 'Hs', 'beryllium': 'Be', 'mercury': 'Hg', 'yttrium': 'Y', 'nickel': 'Ni', 'antimony': 'Sb', 'barium': 'Ba', 'potassium': 'k', 'xenon': 'Xe', 'bohrium': 'Bh', 'helium': 'He', 'dubnium': 'Db', 'strontium': 'Sr', 'bromine': 'Br', 'argon': 'Ar', 'cadmium': 'Cd', 'boron': 'B', 'scandium': 'Sc', 'carbon': 'C', 'palladium': 'Pd', 'silver': 'Ag', 'vanadium': 'v', 'phosphorus': 'P', 'rutherfordium': 'Rf', 'bismuth': 'Bi', 'aluminum': 'Al', 'molybdenum': 'Mo', 'lanthanum': 'La', 'nitrogen': 'N', 'francium': 'Fr', 'gallium': 'Ga', 'zirconium': 'Zr', 'manganese': 'Mn', 'rhodium': 'Ru', 'niobium': 'Nb', 'calcium': 'Ca', 'tantalum': 'Ta', 'magnesium': 'Mg', 'iron': 'Fe', 'tellerium': 'Te', 'cesium': 'Cs', 'indium': 'In'}

inv_symbols = {'Ru': 'rhodium', 'Pd': 'palladium', 'Pt': 'platinum', 'Ni': 'nickel', 'Mg': 'magnesium', 'Na': 'sodium', 'Nb': 'niobium', 'Db': 'dubnium', 'Ne': 'neon', 'Li': 'lithium', 'Pb': 'lead', 'Re': 'rhenium', 'Tl': 'thallium', 'B': 'boron', 'Ra': 'radium', 'Rb': 'rubidium', 'Ti': 'titanium', 'Rn': 'radon', 'Cd': 'cadmium', 'Po': 'polonium', 'Ta': 'tantalum', 'Be': 'beryllium', 'Fr': 'francium', 'Te': 'tellerium', 'Ba': 'barium', 'Os': 'osmium', 'La': 'lanthanum', 'Bh': 'bohrium', 'Ge': 'germanium', 'Zr': 'zirconium', 'Tc': 'technetium', 'Fe': 'iron', 'Br': 'bromine', 'Sr': 'strontium', 'Hf': 'hafnium', 'Hg': 'mercury', 'He': 'helium', 'C': 'carbon', 'Cl': 'chlorine', 'Rf': 'rutherfordium', 'P': 'phosphorus', 'F': 'fluorine', 'I': 'iodine', 'H': 'hydrogen', 'Mo': 'molybdenum', 'v': 'vanadium', 'Ac': 'actinium', 'O': 'oxygen', 'N': 'nitrogen', 'Kr': 'krypton', 'Si': 'silicon', 'Sn': 'tin', 'W': 'tungsten', 'Y': 'yttrium', 'Sb': 'antimony', 'Bi': 'bismuth', 'Al': 'aluminum', 'Sg': 'seaborgium', 'Se': 'selenium', 'Sc': 'scandium', 'Zn': 'zinc', 'Co': 'cobalt', 'Ag': 'silver', 'Mt': 'meitnerium', 'k': 'potassium', 'Ir': 'iridium', 'S': 'sulfur', 'Xe': 'xenon', 'Mn': 'manganese', 'As': 'arsenic', 'Ar': 'argon', 'Au': 'gold', 'At': 'astatine', 'Ga': 'gallium', 'Hs': 'hassium', 'Cs': 'cesium', 'Cr': 'chromium', 'Ca': 'calcium', 'Cu': 'copper', 'In': 'indium'}

Save this file as “data.py”. Take care of the extension. Make sure you are not saving it as data.py.txt.
Open another notepad instance and paste following code in it:

" " " Coder: Ashwin Saxena
  Python Program to get atomic mass of an element aka Periodic-Table Search
" " "

from data import *
from sys import exit
#Needs to return values
#returner = object.molar_mass('ca','na')

def end():
    print "\nThanks for using the Python periodic table search engine!"
    exit(1)
class sort(object):
    def __init__(self):
        decision = raw_input("> ")
        if decision == 'exit' or decision == 'end':
            end()
        try:
            if type(float(decision)) == float:
                decision = float(decision)
                sym =  invatomicmass[decision]
                print "The element with the mass",decision, "is %s, and is abbreviated as %s." % (inv_symbols[sym],sym)

        except ValueError,KeyError:
            pass

        finally:
            pass

       # print "You said %r, which is a %r." % (decision,type(decision))

        if type(decision) == str:
            decision = str(decision)
            if len(decision) <= 2:
                print "You said",decision,",which is also %s, and weighs" % (inv_symbols[decision]), atomic_mass[decision],"."

            if len(decision) > 2:
                print "You said",decision,",which is also %s, and weighs" % (symbols[decision]), atomic_mass[symbols[decision]],"."         

print "Input one of the following: \n\nExact atomic mass\nAbbreviation of element (with first letter in caps)\nFull name of element (no caps)."    

while True:
    print "\n"
    sort()

#End of Program.

Save this file as “Periodic.py” in the same directory where “data.py” is located.

This is a program which displays the atomic mass of any entered Element. The data for elements is stored in “data.py” file, while “Periodic.py” has code to read user input and display that data.

To run this small command line application, Open Command Prompt (if it’s not already open) and enter

python Periodic.py

Let’s see what’s how this code works.

First we take a look at “data.py” file

“atomic_mass”, “symbols” and “inv_symbols” are variables of built-in data type ‘Dictionary’.  Dictionaries are sometimes found in other languages as “associative memories” or “associative arrays”. A dictionary ‘Tel’ can be declared as

tel = {‘jack’: 4098, ‘sape’: 4139, ‘key’: value}

The statement dict((v,k) for k, v in atomic_mass.iteritems()) essiantially, exchanges values of key-value pair so that a key becomes a value and a value becomes a key and stores the resulting dictionary in “invatomicmass” variable.

Looking at Periodic.py file; the first statement is

from data import *

This works imports variables we defined in data.py for use in this code-module.

def end():
    print "\nThanks for using the Python periodic table search engine!"
    exit(1)

end() is a user defined function.

The following code is inside a Try..catch block. Try… catch block is used for exception handling, but we will focus on the code inside that for now.

try:
            if type(float(decision)) == float:
                decision = float(decision)
                sym =  invatomicmass[decision]
                print "The element with the mass",decision, "is %s, and is abbreviated as %s." % (inv_symbols[sym],sym)

        except ValueError,KeyError:
            pass

        finally:
            pass

 

float(decision) is used for type casting variable ‘decision’. type() function returns variable’s type.
Rest of the code is pretty much self explanatory. I urge you to figure some stuff out yourself.

I’ve found that learning by writing your own code and by studying already written code is the best method to learn programming.

I will be posting some more example programs of Python here soon.
Comments appreciated :)