Thursday, March 31, 2016

Checking the type of a variable or object

Recently, I came across to the problem of writing a function that behaves differently according the type of its single input parameter.  Due the fact that Python is a dynamically-typed language, this problem does not look  too easy to me at first glance. But fortunately, Python provides the build- in command  isinstance. This command receives two parameters, the first one is a object and the second is a class or tuple of classes. Then return  true is the object is an instance of the class or of the classes in the tuple. Let us exemplify the use of this function with a routine that print the type of its input parameter,
def printType(x):
    if isinstance(x,(int,long,float,complex)):
        print "It's a number"
        return
    if isinstance(x, str):
        print "It's a string"
        return
    if isinstance(x,list):
        print "It's a list"
        return
    if isinstance(x,dict):
        print "It's a dictionary"
        return
    if isinstance(x,tuple):
        print "It's a tuple"
        return

Wednesday, March 30, 2016

Hello World! (console printing and executable)

Of course the first post of a blog about programming in Python have to be hello world in Python :)
This is the file helloworld.py
#!/usr/bin/env python
print "Hello World"
to execute this file
$python helloworld.py 
Two elements of the helloworld.py script. First, the command print, this command write to the standard output the parameters given. These parameters can be variables, objects (as we are going to discuss in a later post), or as in this case constants. The second element is the first line starting with the charcarter '#'. In Python every character in a line after the symbol '#' is considered as a comment (python interpreter will ignore this). Particularly in our example we have the following comment
#!/usr/bin/env python
This comment is not mandatory, however, it is used if we want to run helloworld.py as an standalone executable. First, we can give execution rights to the file helloworld.py using chmod
$chmod +x helloworld.py 
From now on, we only have to type,
$./helloworld.py 
to execute the helloworld.py.