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"
    if isinstance(x, str):
        print "It's a string"
    if isinstance(x,list):
        print "It's a list"
    if isinstance(x,dict):
        print "It's a dictionary"
    if isinstance(x,tuple):
        print "It's a tuple"

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
#!/usr/bin/env python
print "Hello World"
to execute this file
Two elements of the 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 as an standalone executable. First, we can give execution rights to the file using chmod
$chmod +x 
From now on, we only have to type,
to execute the