CodingBee

A beginners guide to programming and automating stuff

Python – crash course

To install python:

$ yum install python

indentation is important, since code blocks are not encased in any brackets whatsoever.

to access python command line (aka repl) do:

[root@ansibleclient01 ~]# python
Python 2.7.5 (default, Nov 20 2015, 02:00:19)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-4)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> a
Traceback (most recent call last):
  File "", line 1, in 
NameError: name 'a' is not defined
>>> 4
4
>>> 2 + 2
4
>>> 2 + 3
5
>>> x = abc
Traceback (most recent call last):
  File "", line 1, in 
NameError: name 'abc' is not defined
>>> x = 'abc'
>>> x
'abc'
>>>

ctrl+d to exit the python terminal

>>> print('hello world')
hello world
>>>

Python comes included with the standard library. This library is:

https://docs.python.org/2/library/

This shows a list of modules you can ‘import’ into your scripts, without needing to install them separately (using pip utility).

To view help info for the ‘math’ module do:

>>> help('math')
Help on module math:

NAME
    math

FILE
    /usr/lib64/python2.7/lib-dynload/math.so

DESCRIPTION
    This module is always available.  It provides access to the
    mathematical functions defined by the C standard.

FUNCTIONS
    acos(...)
        acos(x)

        Return the arc cosine (measured in radians) of x.

    acosh(...)
        acosh(x)

        Return the hyperbolic arc cosine (measured in radians) of x.

    asin(...)
        asin(x)

        Return the arc sine (measured in radians) of x.

    asinh(...)
        asinh(x)

        Return the hyperbolic arc sine (measured in radians) of x.

To use the math module’s “sqrt” function, you do:

>>> import math
>>> math.sqrt(81)
9.0
>>>

Heres how to run a python script:

[root@ansibleclient01 ~]# cat helloworld.py
print("Hello World!!!")
[root@ansibleclient01 ~]# python helloworld.py
Hello World!!!

You can import a python script, simply by using the import command, followed by the script’s filename, but excluding the .py extension:

[root@ansibleclient01 ~]# python
Python 2.7.5 (default, Nov 20 2015, 02:00:19)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-4)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import helloworldd
Traceback (most recent call last):
  File "", line 1, in 
ImportError: No module named helloworldd
>>> import helloworld
Hello World!!!
>>>

This is useful if your python script has function that you want to make use of. E.g. let’s say we have the following function:

[root@ansibleclient01 ~]# cat helloworld.py
print("Hello World!!!")

def squaringnumber(x):
    return x * x
[root@ansibleclient01 ~]# python
Python 2.7.5 (default, Nov 20 2015, 02:00:19)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-4)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import helloworld
Hello World!!!
>>> helloworld.squaringnumber(9)
81
>>>