Python basics

This tutorial introduces the Python programming language, which is the language used for ChemShell input scripts. If you have never done any programming before, don’t worry! Python is very easy to learn.

Start by typing chemsh to open an interactive ChemShell session. You will see a banner with the version of ChemShell you are using and then a prompt:

>>>

The interactive mode of ChemShell is very similar to starting Python itself, and any python commands can be typed at the prompt as well as those we will see later that are specific to ChemShell. First, let’s try the print() function which outputs text to the display:

>>> print("Hello World!")
Hello World!

Like all programming languages, Python can store data in variables, which can be thought of as labelled containers for information. Values can be assigned to variables using an equals sign =. Variables can contain numbers, text, and many other types of information. The value of a variable can be accessed using the print function:

>>> a = 1
>>> b = "World!"
>>> print("a =", a)
a = 1
>>> print("Hello", b)
Hello World!

The equals sign can also be used to set one variable to the value of another:

>>> a = 3
>>> b = a
>>> print("a =", a, "and b =", b)
a = 3 and b = 3

Arithmetic operations use the symbols + for addition, - for subtraction, * for multiplication and / for division:

>>> x = (6 * 4) - 3
>>> print(x)
21

Another important concept in Python is the list, which are created using square brackets:

>>> c = [1, 2, 3]
>>> print("c =", c)
c = [1, 2, 3]
>>> len(c)
3

The function len() counts the number of items in the list. You can access individual items in a list using an index number in square brackets. It’s important to remember that python lists count from zero:

>>> c[0]
1
>>> c[1]
2
>>> c[2]
3

Simple lists can be generated using the range() function:

>>> a = range(3)
>>> a[0]
0
>>> a[1]
1
>>> a[2]
2

You can loop over lists using the for statement:

>>> a = range(3)
>>> for i in a:
...     print(i)
...
0
1
2

(Note that indentation is important for the commands that follow the for statement. Python uses indentation to indicate that these commands are part of the loop).

Python has another data structure called the dictionary, which consists of key/value pairs. Dictionaries can be defined using curly brackets:

>>> d = { "apple":"green", "banana":"yellow" }
>>> d["apple"]
'green'
>>> d["banana"]
'yellow'

A list of all keys in the dictionary can be printed with the keys() function:

>>> d.keys()
dict_keys(['apple', 'banana'])

You can test for conditions using the if and else statements:

>>> c = 99
>>> if c < 40:
...     print("c is lower than 40")
... else:
...     print("c is higher than 40")
...
c is higher than 40