viernes, 18 de abril de 2014

Python - Basics

Download

python.org

Basics commands

dir(__builtins__)   
Show all the defined functions

help(function_name) 
Show function description

print(string_text)

(__name__)
print the scope in which the functionality is been executed

Define a function

  • Type word def follow by name function with the parameters
  • Type word return with the functionality
Ex:   def f(x):  return x**2

Testing

Inside your function description define the result expected inside the comments.

'''
>>> function_name(parameter_value)
result

>>> function_name(parameter_value_2)
result2

>>>
'''
To run the test cases type

import doctest
doctest.testmod()

You can also run the test cases after your return statement, so each time you include your function the test cases are executed.

Unittest

You can also use Unit Test 
  1. Import unittest
  2. Create a class inherits from unittest.TestCase
    • class TestMain(unittest.TestCase):
  3. Create your test case 
    • def test_name(self):
  4. Use self.assertEqual()
  5. Execute the test cases with unittest.main(exit=False)

Consideration for test cases

Take in consideration these cases:
  • Size
  • Dichotomies 
    • True/False
    • Even/Odd
  • Boundaries
  • Order

Define a class

  1. Type the name of the class and inside the parenthesis the class you want to import
  2. Define your default constructor
  3. Define your methods

class MyClass(str):

    def __init__(param1, param2):
        self.var1 = param1

    def paly(s):
        print (__name__)
        return len(s)

Define methods with default value in parameters

def method_name(param , param2=default_value):

Then you can call method in these ways:

  • method_name(2)  or 
  • method_name(2, 'aa')  

Algorithms 

Each function performs as one of the following functions
  • Lineal 
  • Exponential
  • Logarithmic
log2(n) is the number of times we divide n by 2 in order to reach 1

To evaluate a function python have the library cProfile


Exceptions 

Use the following syntaxis

try:

except  exceptionType:

except exceptionType as e:
   print (e)

As recommendation can use assert to verify preconditions 



No hay comentarios:

Publicar un comentario