El código Python puede ser ejecutado de dos maneras básicas. Como script o desde un interprete interactivo.
#!/usr/bin/python
# first.py
print "The Python tutorial"
# first.py
print "The Python tutorial"
Este es un ejemplo de un pequeño script en Python. Se lanza desde un terminal UNIX.
$ ./first.py
The Python tutorial
The Python tutorial
Interprete interactivo
Otra manera de ejecutar código Python es el interprete interprete interactivo de Python. El interprete Python es bastante util para nuestras pruebas. Cuando queremos probar rápidamente alguna funcionalidad básica del lenguaje Python y no queremos escribir un script completo. Para abrir el interprete interactivo, tendremos que ejecutar el comando de Python en nuestro intérprete de comandos favorito.
$ python
Python 2.7.2+ (default, Jul 20 2012, 22:12:53)
[GCC 4.6.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>
Python 2.7.2+ (default, Jul 20 2012, 22:12:53)
[GCC 4.6.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>
Ahora podremos consultar información util.
>>> credits
Thanks to CWI, CNRI, BeOpen.com, Zope Corporation and a cast of thousands
for supporting Python development. See www.python.org for more information.
>>> copyright
Copyright (c) 2001-2011 Python Software Foundation.
All Rights Reserved.
Copyright (c) 2000 BeOpen.com.
All Rights Reserved.
Copyright (c) 1995-2001 Corporation for National Research Initiatives.
All Rights Reserved.
Copyright (c) 1991-1995 Stichting Mathematisch Centrum, Amsterdam.
All Rights Reserved.
Copyright (c) 2001-2011 Python Software Foundation.
All Rights Reserved.
Copyright (c) 2000 BeOpen.com.
All Rights Reserved.
Copyright (c) 1995-2001 Corporation for National Research Initiatives.
All Rights Reserved.
Copyright (c) 1991-1995 Stichting Mathematisch Centrum, Amsterdam.
All Rights Reserved.
El comando license() ofrece una serie de páginas referidas a la licencia de Python.
Obteniendo ayuda
El comando help ofrece algo de ayuda sobre Python.
>>> help
Type help() for interactive help, or help(object) for help about object.
>>>
Type help() for interactive help, or help(object) for help about object.
>>>
Por ejemplo, si escribimos help(True), obtendremos información sobre objetos de tipo bool.
Help on bool object:
class bool(int)
| bool(x) -> bool
|
| Returns True when the argument x is true, False otherwise.
| The builtins True and False are the only two instances of the class bool.
| The class bool is a subclass of the class int, and cannot be subclassed.
|
| Method resolution order:
| bool
| int
| object
|
| Methods defined here:
|
| __and__(...)
| x.__and__(y) <==> x&y
...
class bool(int)
| bool(x) -> bool
|
| Returns True when the argument x is true, False otherwise.
| The builtins True and False are the only two instances of the class bool.
| The class bool is a subclass of the class int, and cannot be subclassed.
|
| Method resolution order:
| bool
| int
| object
|
| Methods defined here:
|
| __and__(...)
| x.__and__(y) <==> x&y
...
Si escribimos help() obtenemos el modo interactivo de ayuda del interprete.
>>> help()
Welcome to Python 2.7! This is the online help utility.
If this is your first time using Python, you should definitely check out
the tutorial on the Internet at http://docs.python.org/tutorial/.
Enter the name of any module, keyword, or topic to get help on writing
Python programs and using Python modules. To quit this help utility and
return to the interpreter, just type "quit".
To get a list of available modules, keywords, or topics, type "modules",
"keywords", or "topics". Each module also comes with a one-line summary
of what it does; to list the modules whose summaries contain a given word
such as "spam", type "modules spam".
help>
Welcome to Python 2.7! This is the online help utility.
If this is your first time using Python, you should definitely check out
the tutorial on the Internet at http://docs.python.org/tutorial/.
Enter the name of any module, keyword, or topic to get help on writing
Python programs and using Python modules. To quit this help utility and
return to the interpreter, just type "quit".
To get a list of available modules, keywords, or topics, type "modules",
"keywords", or "topics". Each module also comes with a one-line summary
of what it does; to list the modules whose summaries contain a given word
such as "spam", type "modules spam".
help>
El comando keywords proporciona una lista con palabras clave disponibles en el lenguaje de programación Python.
help> keywords
Here is a list of the Python keywords. Enter any keyword to get more help.
and elif if print
as else import raise
assert except in return
break exec is try
class finally lambda while
continue for not with
def from or yield
del global pass
Here is a list of the Python keywords. Enter any keyword to get more help.
and elif if print
as else import raise
assert except in return
break exec is try
class finally lambda while
continue for not with
def from or yield
del global pass
El comando modules proporciona una lista de módulos disponibles. Una vez más, al escribir un nombre de módulo se proporcionará ayuda adicional.
Por último, tenemos el comando topics.
help> topics
Here is a list of available topics. Enter any topic name to get more help.
ASSERTION DEBUGGING LITERALS SEQUENCEMETHODS2
ASSIGNMENT DELETION LOOPING SEQUENCES
ATTRIBUTEMETHODS DICTIONARIES MAPPINGMETHODS SHIFTING
ATTRIBUTES DICTIONARYLITERALS MAPPINGS SLICINGS
AUGMENTEDASSIGNMENT DYNAMICFEATURES METHODS SPECIALATTRIBUTES
BACKQUOTES ELLIPSIS MODULES SPECIALIDENTIFIERS
BASICMETHODS EXCEPTIONS NAMESPACES SPECIALMETHODS
BINARY EXECUTION NONE STRINGMETHODS
BITWISE EXPRESSIONS NUMBERMETHODS STRINGS
BOOLEAN FILES NUMBERS SUBSCRIPTS
CALLABLEMETHODS FLOAT OBJECTS TRACEBACKS
CALLS FORMATTING OPERATORS TRUTHVALUE
CLASSES FRAMEOBJECTS PACKAGES TUPLELITERALS
CODEOBJECTS FRAMES POWER TUPLES
COERCIONS FUNCTIONS PRECEDENCE TYPEOBJECTS
COMPARISON IDENTIFIERS PRINTING TYPES
COMPLEX IMPORTING PRIVATENAMES UNARY
CONDITIONAL INTEGER RETURNING UNICODE
CONTEXTMANAGERS LISTLITERALS SCOPING
CONVERSIONS LISTS SEQUENCEMETHODS1
Here is a list of available topics. Enter any topic name to get more help.
ASSERTION DEBUGGING LITERALS SEQUENCEMETHODS2
ASSIGNMENT DELETION LOOPING SEQUENCES
ATTRIBUTEMETHODS DICTIONARIES MAPPINGMETHODS SHIFTING
ATTRIBUTES DICTIONARYLITERALS MAPPINGS SLICINGS
AUGMENTEDASSIGNMENT DYNAMICFEATURES METHODS SPECIALATTRIBUTES
BACKQUOTES ELLIPSIS MODULES SPECIALIDENTIFIERS
BASICMETHODS EXCEPTIONS NAMESPACES SPECIALMETHODS
BINARY EXECUTION NONE STRINGMETHODS
BITWISE EXPRESSIONS NUMBERMETHODS STRINGS
BOOLEAN FILES NUMBERS SUBSCRIPTS
CALLABLEMETHODS FLOAT OBJECTS TRACEBACKS
CALLS FORMATTING OPERATORS TRUTHVALUE
CLASSES FRAMEOBJECTS PACKAGES TUPLELITERALS
CODEOBJECTS FRAMES POWER TUPLES
COERCIONS FUNCTIONS PRECEDENCE TYPEOBJECTS
COMPARISON IDENTIFIERS PRINTING TYPES
COMPLEX IMPORTING PRIVATENAMES UNARY
CONDITIONAL INTEGER RETURNING UNICODE
CONTEXTMANAGERS LISTLITERALS SCOPING
CONVERSIONS LISTS SEQUENCEMETHODS1
Código Python
Ahora vamos a ver los puntos positivos reales de la intérprete de Python.
El intérprete de Python se puede utilizar como una calculadora. Cada expresión se ejecuta de inmediato y el resultado se muestra en la pantalla.
>>> a = 3
>>> b = 4
>>> a**b
81
>>> a == b
False
>>> a < b
True
>>>
>>> b = 4
>>> a**b
81
>>> a == b
False
>>> a < b
True
>>>
>>> import random
>>> dir(random)
['BPF', 'LOG4', 'NV_MAGICCONST', 'RECIP_BPF', 'Random', 'SG_MAGICCONST',
'SystemRandom', 'TWOPI', 'WichmannHill', '_BuiltinMethodType', '_MethodType',
'__all__', '__builtins__', '__doc__', '__file__', '__name__', '_acos',
'_ceil', '_cos', '_e', '_exp', '_hexlify', '_inst', '_log', '_pi', '_random',
'_sin', '_sqrt', '_test', '_test_generator', '_urandom', '_warn',
'betavariate', 'choice', 'expovariate', 'gammavariate', 'gauss',
'getrandbits', 'getstate', 'jumpahead', 'lognormvariate', 'normalvariate',
'paretovariate', 'randint', 'random', 'randrange', 'sample', 'seed',
'setstate', 'shuffle', 'uniform', 'vonmisesvariate', 'weibullvariate']
>>>
>>> dir(random)
['BPF', 'LOG4', 'NV_MAGICCONST', 'RECIP_BPF', 'Random', 'SG_MAGICCONST',
'SystemRandom', 'TWOPI', 'WichmannHill', '_BuiltinMethodType', '_MethodType',
'__all__', '__builtins__', '__doc__', '__file__', '__name__', '_acos',
'_ceil', '_cos', '_e', '_exp', '_hexlify', '_inst', '_log', '_pi', '_random',
'_sin', '_sqrt', '_test', '_test_generator', '_urandom', '_warn',
'betavariate', 'choice', 'expovariate', 'gammavariate', 'gauss',
'getrandbits', 'getstate', 'jumpahead', 'lognormvariate', 'normalvariate',
'paretovariate', 'randint', 'random', 'randrange', 'sample', 'seed',
'setstate', 'shuffle', 'uniform', 'vonmisesvariate', 'weibullvariate']
>>>
Con la ayuda de la cadena especial __doc__, podemos obtener ayuda sobre una función específica.
>>> print random.seed.__doc__
Initialize internal state from hashable object.
None or no argument seeds from current time or from an operating
system specific randomness source if available.
If a is not None or an int or long, hash(a) is used instead.
>>>
Initialize internal state from hashable object.
None or no argument seeds from current time or from an operating
system specific randomness source if available.
If a is not None or an int or long, hash(a) is used instead.
>>>
>>> locals()
{'__builtins__':, '__name__': '__main__',
'random':, '__doc__': None}
{'__builtins__':
'random':
>>> class Car:
... pass
...
>>> def function():
... pass
...
>>> for i in range(5):
... print i
...
0
1
2
3
4
>>>
... pass
...
>>> def function():
... pass
...
>>> for i in range(5):
... print i
...
0
1
2
3
4
>>>
>>> import os
>>> os.getcwd()
'/home/vronskij/programming/python'
>>> os.system('ls')
empty.pyc fibonacci.pyc ifyouwantme~ monica old perl.pl
ruby.rb stopiter.py tests works
>>> os.getcwd()
'/home/vronskij/programming/python'
>>> os.system('ls')
empty.pyc fibonacci.pyc ifyouwantme~ monica old perl.pl
ruby.rb stopiter.py tests works
Por último, queremos salir del intérprete. Podemos salir del intérprete de varias maneras:
- Ctrl+D
- quit()
También podemos salir del intérprete programáticamente.
>>> raise SystemExit
$
o$
>>> import sys
>>> sys.exit()
$
>>> sys.exit()
$
El Zen de Python
El Zen de Python es un conjunto de reglas de cómo escribir buen código Python. Refleja de alguna manera la filosofía del lenguaje.
>>> import this
The Zen of Python, by Tim Peters
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
The Zen of Python, by Tim Peters
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
*en español sería algo asi
El Zen de Python, por Tim Peters
Elegante es mejor que feo.
Explícito es mejor que implícito.
Simple es mejor que complejo.
Complejo es mejor que complicado.
Plano es mejor que anidado.
Disperso es mejor que denso.
La legibilidad cuenta.
Los casos especiales no son lo suficientemente especiales como para romper las reglas.
Aunque practicidad roza la pureza.
Los errores nunca deberían pasar inadvertidos.
A menos que se silencien explícitamente.
Ante la ambigüedad, rechaza la tentación de adivinar.
Debe haber una --y preferiblemente de una sola-- manera obvia de hacerlo.
Aunque esa manera puede no ser obvia en un primer momento a menos que seas holandés.
Ahora es mejor que nunca.
Aunque nunca suele ser mejor que *justo* ahora.
Si la aplicación es difícil de explicar, es una mala idea.
Si la aplicación es fácil de explicar, puede ser una buena idea.
Los espacios de nombres son una grandisima idea - vamos a hacer más de esos!
El Zen de Python, por Tim Peters
Elegante es mejor que feo.
Explícito es mejor que implícito.
Simple es mejor que complejo.
Complejo es mejor que complicado.
Plano es mejor que anidado.
Disperso es mejor que denso.
La legibilidad cuenta.
Los casos especiales no son lo suficientemente especiales como para romper las reglas.
Aunque practicidad roza la pureza.
Los errores nunca deberían pasar inadvertidos.
A menos que se silencien explícitamente.
Ante la ambigüedad, rechaza la tentación de adivinar.
Debe haber una --y preferiblemente de una sola-- manera obvia de hacerlo.
Aunque esa manera puede no ser obvia en un primer momento a menos que seas holandés.
Ahora es mejor que nunca.
Aunque nunca suele ser mejor que *justo* ahora.
Si la aplicación es difícil de explicar, es una mala idea.
Si la aplicación es fácil de explicar, puede ser una buena idea.
Los espacios de nombres son una grandisima idea - vamos a hacer más de esos!
Las reglas se pueden leer mediante el lanzamiento de import this.
En este capítulo hemos visto intérprete interactivo de Python.
Original en ZetCode