Search This Blog

Tuesday, March 25, 2014

Print a hollow diamond - with numbers

if __name__ == "__main__" :
        act_size = int(input("Enter the size of the diamond : "))
        size_max = 2*act_size - 1
        i_size = 2 * act_size
        for j in range(0,i_size):
            for i in range(i_size):
                if pos > act_size - level+1 and pos <=act_size+level-1 and level<=act_size :
                    print(" ", end='')
                elif pos <= act_size and size < 2*act_size and level<=act_size :
                    print(size, end='')
                    size += 2
                elif pos > act_size and pos <= i_size and level<=act_size :
                    size -= 2
                    print(size, end='')
                if level > act_size and pos <= level - act_size:                 
                    size_max += 2                   
                elif level > act_size and pos > i_size - level + act_size :
                    size_max -= 2
                elif level > act_size:
                    print(" ",end='')
                pos += 1
            size_max = 2*(i_size-level)-1
            size = (2*level) + 1
            level += 1
    except :
        print("ERROR: Only numbers are accepted")


Sunday, March 16, 2014


None is :

  • a special constant in python
  • a null value
  • of datatype NoneType

None is not:

  • 0
  • is not an empty string
  • is not the same as False

You can:

  • compare None to anything other than None always returns False.
  • assign None to any variable
You cannot create other NoneType objects. All variables with a value of None are equal to each other.

ImportError handling

You run in to import errors by using the try...except blocks.
You run in to this error when the module that you are trying to import does not exist in the sys.path. However, if you want to gracefully continue your execution even if there is an import error (and if this what your program expects) then you can handle it using except.

try: import abcexcept ImportError: print("It is still OK to continue")


You can also chose to import sys path 

Raising an Exception

Python uses try...except blocks to handle exceptions and raise statement to generate exceptions

We can raise exceptions by using the raise command of python.


raise [ Exception , [,args [,Traceback]]]

Exception : Type of exception like NameError or ValueError.
args :  value of exception argument
Traceback : It is very rarely uses and is the traceback object exception.

if size < 1 :
raise ValueError('Number must not be negative')

Traceback (most recent call last):
  File "<pyshell#31>", line 2, in <module>
    raise ValueError('Number must not be negative')
ValueError: Number must not be negatrive

In reality, exceptions are implemented as classes and this raise statement is actually creating an instance of ValueError class and passing the string 'Number must not be negative' to its initialization method.

import search path

Python looks are several directories when you try to import a module. It mainly searched the directories defined in sys.path. This is a list and you can see it as follows:

>>> import sys
>>> sys.path
['', 'C:\\Python33\\Lib\\idlelib', 'C:\\Python33\\lib\\site-packages\\selenium-2.40.0-py3.3.egg', 'C:\\Windows\\system32\\', 'C:\\Python33\\DLLs', 'C:\\Python33\\lib', 'C:\\Python33', 'C:\\Python33\\lib\\site-packages']

If you want it to see in other directories, you can make it search it by using the sys.path.insert( 0, new_path ). This is very useful, if you want to import your own custom module.

Documentation Strings

Everything between the triple quotes is the function's docstring, which documents what the function does.

A docstring must be the first thing defined in a function (on the next line after the function declaration).

The docstring is available at runtime as an attribute of the function (.__doc__)

""" This is how you declare a doc string.
This even goes to multiple lines.
The docstring ends here. It even ends with a triplequote"""

Facts of python

  • Python is an interpreted language
  • In python, variables are never explicitly typed
  • Python doesn't let you reference a variable that has never been used
  • Lists are mutable and tuples are immutable
  • Python is object oriented. In python everything is an object in the sense that is can be assigned to a variable or passed as an argument to a function.
  • In python functions, modules, classes and individual instances of class are first-class-objects.
  • You can pass an entire module as an argument to a function
  • Python has no begin or end statement, no curly braces to say where the function (or any other code block) starts and where it end. The only delimiter is : ( def function_name () : ) and indentation
  • There are no subroutines in python. Everything is a function and all the functions return a value even if it is 'None'.
  • Function is also an object
  • All the functions start with 'def' 
  • Python functions doesn't define a return datatype. Python functions so not specify the datatype of their return value ; they don't even specify whether they return a value. In fact, every python function returns a value ; if the function ever executes a return statement, it will return that value ; otherwise, it will return None, the python null value.
  • Python keeps track of the datatype internally
  • The docstring (what ever is between """ and the next """ ) is available as an attribute of the function at runtime (.__doc__)
  • __name__ will give you the module name (actually the file name) without the directory path. By default, it is __main__ . If you do "import os ; print(os.__name__)" , you'll get "os" as the output
  • Python searches the directories defined in sys.path when you try to import a module. You can make it search a new path by using sys.path.insert(0, <new_path>)
  • Python uses try...except blocks to handle exceptions and raise statement to generate exceptions
  • The Boolean value for an empty tuple/list is false.
  • sets are unique bag of values. Example: a_set={1,2,3}. If you try to add a duplicate value to a set, it is ignored and you wouldn't even get an error.

Assign default values for function arguments

 def are_we_going (what_time, go_to_movie="Yes") : print(go_to_movie + ". We are going  at " + what_time)are_we_going("five")

>>> Yes. We are going at five

def are_we_going (what_time, go_to_movie="Yes") :

In the above declaration, we have assigned the value of go_to_movie as Yes. This will be the default value, if no value is passed to this argument while calling this function.

Another important thing to note is that the default arguments should follow the non-default arguments. If this rule is not followed, you will get the following error:

SyntaxError: non-default argument follows default argument


Use 'if' to assign a Value

You can use 'if' effectively to assign a value to a variable. See the following example:

go_to_movie = Yes if movie_is_harry_potter else No

 The value of go_to_movie is set to Yes, if movie_is_harry_potter=True or else it will be set to 'No'.

Please note that movie_is_harry_potter takes either True / False but not any other value if you are planning to use it in the 'if' statement here.