Python

Basics

Fuertemente tipado y dinámico


In [61]:
a = 5
b = 6.0
a + b
hi = 'hello'

#hi+a

a,b = 3,6
print a,b
print range(3)
(MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY) = range(7)


3 6
[0, 1, 2]

Functions


In [9]:
def hello_function(name ='Sergi'):
    """ I hate documentation buuuuuuuuu"""
    print 'hello '+name
    
hello_function()
hello_function('Someone')


hello Sergi
hello Someone
 I hate documentation buuuuuuuuu

All is an Object


In [10]:
nice = 'F**** awesome!!'
print nice.__doc__


str(object='') -> string

Return a nice string representation of the object.
If the argument is a string, the return value is the same object.

Strings


In [77]:
multi = """
This  is a
multiline sentence guys
"""

#substrins
animal = "elephant"
print animal[:1]
print animal[2:]
print animal[3:4]

#reverse
print animal[-1]
print animal[2:-1]

#operations
print 'hi'*3


e
ephant
p
t
ephan
hihihi

In [29]:
word = "supercalifragilisticoexpialidocious"
print len(word)

ImSpanish = 'Yo soy español'
print ImSpanish
ImSpanish = u'Yo soy español'
print ImSpanish

#format
instrument = 'guitar'
sentence = 'I like playing {0}'.format(instrument)
print sentence

instrument = 'with fire'
sentence = 'I like playing {instrument}'.format(instrument=instrument)
print sentence


35
Yo soy español
Yo soy español
I like playing guitar
I like playing with fire

modules


In [20]:
import os
print os.__name__
print os.__file__
print os.__package__
dir(os)
#os.path.abspath(__file__)
#import sys
#sys.path.append("/home/me/mypy")

#if __name__ == "__main__":
#    run_my_app()


os
/usr/lib/python2.7/os.pyc
None
Out[20]:
['EX_CANTCREAT',
 'EX_CONFIG',
 'EX_DATAERR',
 'EX_IOERR',
 'EX_NOHOST',
 'EX_NOINPUT',
 'EX_NOPERM',
 'EX_NOUSER',
 'EX_OK',
 'EX_OSERR',
 'EX_OSFILE',
 'EX_PROTOCOL',
 'EX_SOFTWARE',
 'EX_TEMPFAIL',
 'EX_UNAVAILABLE',
 'EX_USAGE',
 'F_OK',
 'NGROUPS_MAX',
 'O_APPEND',
 'O_ASYNC',
 'O_CREAT',
 'O_DIRECT',
 'O_DIRECTORY',
 'O_DSYNC',
 'O_EXCL',
 'O_LARGEFILE',
 'O_NDELAY',
 'O_NOATIME',
 'O_NOCTTY',
 'O_NOFOLLOW',
 'O_NONBLOCK',
 'O_RDONLY',
 'O_RDWR',
 'O_RSYNC',
 'O_SYNC',
 'O_TRUNC',
 'O_WRONLY',
 'P_NOWAIT',
 'P_NOWAITO',
 'P_WAIT',
 'R_OK',
 'SEEK_CUR',
 'SEEK_END',
 'SEEK_SET',
 'ST_APPEND',
 'ST_MANDLOCK',
 'ST_NOATIME',
 'ST_NODEV',
 'ST_NODIRATIME',
 'ST_NOEXEC',
 'ST_NOSUID',
 'ST_RDONLY',
 'ST_RELATIME',
 'ST_SYNCHRONOUS',
 'ST_WRITE',
 'TMP_MAX',
 'UserDict',
 'WCONTINUED',
 'WCOREDUMP',
 'WEXITSTATUS',
 'WIFCONTINUED',
 'WIFEXITED',
 'WIFSIGNALED',
 'WIFSTOPPED',
 'WNOHANG',
 'WSTOPSIG',
 'WTERMSIG',
 'WUNTRACED',
 'W_OK',
 'X_OK',
 '_Environ',
 '__all__',
 '__builtins__',
 '__doc__',
 '__file__',
 '__name__',
 '__package__',
 '_copy_reg',
 '_execvpe',
 '_exists',
 '_exit',
 '_get_exports_list',
 '_make_stat_result',
 '_make_statvfs_result',
 '_pickle_stat_result',
 '_pickle_statvfs_result',
 '_spawnvef',
 'abort',
 'access',
 'altsep',
 'chdir',
 'chmod',
 'chown',
 'chroot',
 'close',
 'closerange',
 'confstr',
 'confstr_names',
 'ctermid',
 'curdir',
 'defpath',
 'devnull',
 'dup',
 'dup2',
 'environ',
 'errno',
 'error',
 'execl',
 'execle',
 'execlp',
 'execlpe',
 'execv',
 'execve',
 'execvp',
 'execvpe',
 'extsep',
 'fchdir',
 'fchmod',
 'fchown',
 'fdatasync',
 'fdopen',
 'fork',
 'forkpty',
 'fpathconf',
 'fstat',
 'fstatvfs',
 'fsync',
 'ftruncate',
 'getcwd',
 'getcwdu',
 'getegid',
 'getenv',
 'geteuid',
 'getgid',
 'getgroups',
 'getloadavg',
 'getlogin',
 'getpgid',
 'getpgrp',
 'getpid',
 'getppid',
 'getresgid',
 'getresuid',
 'getsid',
 'getuid',
 'initgroups',
 'isatty',
 'kill',
 'killpg',
 'lchown',
 'linesep',
 'link',
 'listdir',
 'lseek',
 'lstat',
 'major',
 'makedev',
 'makedirs',
 'minor',
 'mkdir',
 'mkfifo',
 'mknod',
 'name',
 'nice',
 'open',
 'openpty',
 'pardir',
 'path',
 'pathconf',
 'pathconf_names',
 'pathsep',
 'pipe',
 'popen',
 'popen2',
 'popen3',
 'popen4',
 'putenv',
 'read',
 'readlink',
 'remove',
 'removedirs',
 'rename',
 'renames',
 'rmdir',
 'sep',
 'setegid',
 'seteuid',
 'setgid',
 'setgroups',
 'setpgid',
 'setpgrp',
 'setregid',
 'setresgid',
 'setresuid',
 'setreuid',
 'setsid',
 'setuid',
 'spawnl',
 'spawnle',
 'spawnlp',
 'spawnlpe',
 'spawnv',
 'spawnve',
 'spawnvp',
 'spawnvpe',
 'stat',
 'stat_float_times',
 'stat_result',
 'statvfs',
 'statvfs_result',
 'strerror',
 'symlink',
 'sys',
 'sysconf',
 'sysconf_names',
 'system',
 'tcgetpgrp',
 'tcsetpgrp',
 'tempnam',
 'times',
 'tmpfile',
 'tmpnam',
 'ttyname',
 'umask',
 'uname',
 'unlink',
 'unsetenv',
 'urandom',
 'utime',
 'wait',
 'wait3',
 'wait4',
 'waitpid',
 'walk',
 'write']

Dictionaries


In [73]:
a_dictionary = {'aKey':'aValue', 'anotherKey': 'anotherValue' }
#print dir(a_dictionary)

print a_dictionary
print a_dictionary['aKey']


#modify an element
a_dictionary['aKey'] = 'valueChanged'
print a_dictionary['aKey']

#add an element several types
a_dictionary['aNumber'] = 4
print a_dictionary

#for
for key,value in a_dictionary.items():
    print key, value
    
#remove items
del a_dictionary['aNumber']
print a_dictionary

a_dictionary.clear()
print a_dictionary


{'aKey': 'aValue', 'anotherKey': 'anotherValue'}
aValue
valueChanged
{'aNumber': 4, 'aKey': 'valueChanged', 'anotherKey': 'anotherValue'}
aNumber 4
aKey valueChanged
anotherKey anotherValue
{'aKey': 'valueChanged', 'anotherKey': 'anotherValue'}
{}

Lists


In [51]:
#print dir(list)

list = [1,2,'three']
print list
print list[0]
print list[1:]
print list[-1:]


['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__delslice__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getslice__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__setslice__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
[1, 2, 'three']
1
[2, 'three']
['three']

append and insert


In [ ]:
list.append('added item')
print list

list.insert(1,'insertAnItem')
print list
list.insert(1,['insertItemList','anotherAnotherItemFromAddedList'])
print list
list[1:1] = ['insert','twoItems']
print list

searching


In [ ]:
list = ['firstItem','secondItem','thirdItem']
print list.index('secondItem')
print list.index('thirdItem')
#list.index('fourthItem')

print 'fourthItem' in list
print 'secondItem' in list

remove


In [54]:
list = ['firstItem','secondItem','thirdItem']
list.remove('secondItem')
print list
last_element = list.pop()
print last_element


['firstItem', 'thirdItem']
thirdItem

operations


In [76]:
a = [1,2]
b = [3,4]
c = a+b
print c

print a*2


[1, 2, 3, 4]
[1, 2, 1, 2]
hihihi

Tuplas


In [ ]:
t = (1,'two','last')
#print dir(t)

print t[1]
print t[-1]
print t[1:3]

List for comprehesion


In [ ]:
li = [3,4,5,6]
#li = range(3,7)
print li
print [item*10 for item in li]
print [item*10 for item in li if item > 4]

robots = { 'Mazinger': 'Z', 'Robotech': '3000'}
#print [ 'Robot {name} is type {type}'.format(name=key,type=value) for key,value in robots.items()]

Introspection

dir and callable


In [93]:
import types

print dir(types)
l = [0,1]
print types.BooleanType == type(l)
print types.ListType == type(l)

print callable(l)
print callable(l.append)


['BooleanType', 'BufferType', 'BuiltinFunctionType', 'BuiltinMethodType', 'ClassType', 'CodeType', 'ComplexType', 'DictProxyType', 'DictType', 'DictionaryType', 'EllipsisType', 'FileType', 'FloatType', 'FrameType', 'FunctionType', 'GeneratorType', 'GetSetDescriptorType', 'InstanceType', 'IntType', 'LambdaType', 'ListType', 'LongType', 'MemberDescriptorType', 'MethodType', 'ModuleType', 'NoneType', 'NotImplementedType', 'ObjectType', 'SliceType', 'StringType', 'StringTypes', 'TracebackType', 'TupleType', 'TypeType', 'UnboundMethodType', 'UnicodeType', 'XRangeType', '__builtins__', '__doc__', '__file__', '__name__', '__package__']
False
True
Out[93]:
True

getattr


In [110]:
hi = 'hi bro'
print getattr(hi,'split')


l = ['hi','bro']
print '-'.join(l)
print getattr('_','join')(l)

import types
print type(getattr(l,'index'))
type(getattr(l,'index')) == types.BuiltinFunctionType

print getattr(l, 'sort').__doc__


<built-in method split of str object at 0x27fb4b0>
hi-bro
hi_bro
<type 'builtin_function_or_method'>
L.sort(cmp=None, key=None, reverse=False) -- stable sort *IN PLACE*;
cmp(x, y) -> -1, 0, 1

OOP


In [5]:
class Vehicle:
    def start(self):
        print 'RUNNNNNNNNN'
        
    def accelerate(self):
        print  'speed of light'
        
vehicle = Vehicle()
vehicle.start()


class Car(Vehicle):
    wheels = 4
    speed = 0
    accel = 2
    def __init__(self, brand):
        self.brand = brand
        
    def accelerate(self):
        self.speed += self.accel 
        
    def get_velocity(self):
        return self.speed;
    
car = Car('Jonda')
car.start()
car.accelerate()
print car.get_velocity()
car.accelerate()
print car.get_velocity()

class Robot:
    def __init__(self, name, weapon):
        self.name = name
        self.weapon = weapon
        
    def shot(self):
        print 'shotgun devastator with my weapon {weapon}'.format(weapon = self.weapon)
        
    def __str__(self):
        return 'I am {0} and I am going to destroit you with my {1}'.format(self.name, self.weapon)
    

wally = Robot('Wally', 'BigGun')
wally.shot()

class Transformer(Car,Robot):
    def __init__(self,brand, name, weapon):
        self.name = name
        self.brand = brand
        self.weapon = weapon

optimus = Transformer('Pegasus','Optimus','EvilGrenade')

print optimus
optimus.start()


#Others : __new__(cls, args)  __del__(self)  __str__(self) __cmp__(self, arg) __len__(self)
from IPython.display import Image
i = Image(filename='files/Optimus-Prime.jpg')

i


RUNNNNNNNNN
RUNNNNNNNNN
2
4
shotgun devastator with my weapon BigGun
I am Optimus and I am going to destroit you with my EvilGrenade
RUNNNNNNNNN
Out[5]: