PDF de programación - Tutorial de Python

Imágen de pdf Tutorial de Python

Tutorial de Pythongráfica de visualizaciones

Publicado el 3 de Septiembre del 2019
849 visualizaciones desde el 3 de Septiembre del 2019
882,8 KB
153 paginas
Creado hace 14a (04/07/2009)
Tutorial de Python

The Python tutorial

Release:

2.5.2

Date:

July 04, 2009

Python is an easy to learn, powerful programming language. It has efficient high-
level data structures and a simple but effective approach to object-oriented
programming. Python's elegant syntax and dynamic typing, together with its
interpreted nature, make it an ideal language for scripting and rapid application
development in many areas on most platforms.

The Python interpreter and the extensive standard library are freely available in
source or binary form for all major platforms from the Python Web site,
http://www.python.org/, and may be freely distributed. The same site also con
tains distributions of and pointers to many free third party Python modules,
programs and tools, and additional documentation.

The Python interpreter is easily extended with new functions and data types
implemented in C or C++ (or other languages callable from C). Python is also
suitable as an extension language for customizable applications.

This tutorial introduces the reader informally to the basic concepts and features
of the Python language and system. It helps to have a Python interpreter handy
for hands-on experience, but all examples are self-contained, so the tutorial can
be read off-line as well.

For a description of standard objects and modules, see the Python Library
Reference document. The Python Reference Manual gives a more formal defini
tion of the language. To write extensions in C or C++, read Extending and
Embedding the Python Interpreter and Python/C API Reference. There are also
several books covering Python in depth.

This tutorial does not attempt to be comprehensive and cover every single
feature, or even every commonly used feature. Instead, it introduces many of
Python's most noteworthy features, and will give you a good idea of the lan

1

Tutorial de Python

guage's flavor and style. After reading it, you will be able to read and write Python
modules and programs, and you will be ready to learn more about the various
Python library modules described in the Python Library Reference.

The glossary is also worth going through.

2

Tutorial de Python

Saciando tu apetito

Si trabajas mucho con computadoras, eventualmente encontrarás que te gust
aría automatizar alguna tarea. Por ejemplo, podrías desear realizar una
búsqueda y reemplazo en un gran número de archivos de texto, o renombrar y
reorganizar un montón de archivos con fotos de una manera compleja. Tal vez
quieras escribir alguna pequeña base de datos personalizada, personalizada, o
una aplicación especializada con interfaz gráfica, o un juego simple.

Si eres un desarrollador de software profesional, tal vez necesites trabajar con
varias bibliotecas de C/C++/Java pero encuentres que se hace lento el ciclo
usual de escribir/compilar/testear/recompilar. Tal vez estás escribiendo una
batería de pruebas para una de esas bibliotecas y encuentres que escribir el
código de testeo se hace una tarea tediosa. O tal vez has escrito un programa al
que le vendría bien un lenguaje de extensión, y no quieres diseñar/implementar
todo un nuevo lenguaje para tu aplicación.

Python es el lenguaje justo para ti.

Podrías escribir un script en el interprete de comandos o un archivo por lotes de
Windows para algunas de estas tareas, pero los scripts se lucen para mover
archivos de un lado a otro y para modificar datos de texto, no para aplicaciones
con interfaz de usuario o juegos. Podrías escribir un programa en C/C++/Java,
pero puede tomar mucho tiempo de desarrollo obtener al menos un primer
borrador del programa. Python es más fácil de usar, está disponible para sistem
as operativos Windows, MacOS X y Unix, y te ayudará a realizar tu tarea más
velozmente.

Python es fácil de usar, pero es un lenguaje de programación de verdad,
ofreciendo mucho mucho mayor estructura y soporte para programas grandes
que lo que lo que pueden ofrecer los scripts de Unix o archivos por lotes. Por
otro lado, Python ofrece mucho más chequeo de error que C, y siendo un
lenguaje de muy alto nivel, tiene tipos de datos de alto nivel incorporados como
ser arreglos de tamaño flexible y diccionarios. Debido a sus tipos de datos más

3

Tutorial de Python

generales Python puede aplicarse a un dominio de problemas mayor que Awk o
incluso Perl, y aún así muchas cosas siguen siendo al menos igual de fácil en
Python que en esos lenguajes.

Python te permite separar tu programa en módulos que pueden reusarse en
otros programas en Python. Viene con una gran colección de módulos estándar
que puedes usar como base de tus programas --- o como ejemplos para empezar
a aprender a programar en Python. Algunos de estos módulos proveen cosas
como entrada/salida a archivos, llamadas al sistema, sockets, e incluso inter
faces a sistemas de interfaz gráfica de usuario como Tk.

Python es un lenguaje interpretado, lo cual puede ahorrarte mucho tiempo
durante el desarrollo ya que no es necesario compilar ni enlazar. El interprete
puede usarse interactivamente, lo que facilita experimentar con características
del lenguaje, escribir programas descartables, o probar funciones cuando se
hace desarrollo de programas de abajo hacia arriba. Es también una calculadora
de escritorio práctica.

Python permite escribir programas compactos y legibles. Los programas en
Python son típicamente más cortos que sus programas equivalentes en C, C++
o Java por varios motivos:

los tipos de datos de alto nivel permiten expresar operaciones
complejas en una sola instrucción;
la agrupación de instrucciones se hace por indentación en vez de llaves
de apertura y cierre.

no es necesario declarar variables ni argumentos.

Python es extensible: si ya sabes programar en C es fácil agregar una nueva
función o módulo al intérprete, ya sea para realizar operaciones críticas a
velocidad máxima, o para enlazar programas Python con bibliotecas que tal vez
sólo estén disponibles en forma binaria (por ejemplo bibliotecas gráficas es
pecíficas de un fabricante). Una vez que estés realmente entusiasmado, puedes
enlazar el intérprete Python en una aplicación hecha en C y usarlo como lenguaje
de extensión o de comando para esa aplicación.

4



Tutorial de Python

Por cierto, el lenguaje recibe su nombre del programa de televisión de la BBC
"Monty Python's Flying Circus" y no tiene nada que ver con reptiles. Hacer
referencias a sketches de Monty Python en la documentación no sólo esta
permitido, sino que también está bien visto!

Ahora que ya estás emocionada con Python, querrás verlo en más detalle. Cómo
la mejor forma de aprender un lenguaje es usarlo, el tutorial te invita a que
juegues con el intérprete Python a medida que vas leyendo.

En el próximo capítulo se explicará la mecánica de uso del intérprete. Ésta es
información bastante mundana, pero es esencial para poder probar los ejemplos
que aparecerán más adelante.

El resto del tutorial introduce varias características del lenguaje y el sistema
Python a través de ejemplos, empezando con expresiones, instrucciones y tipos
de datos simples, pasando por funciones y módulos, y finalmente tocando
conceptos avanzados como excepciones y clases definidas por el usuario.

5

Tutorial de Python

Using the Python Interpreter

Invoking the Interpreter

The Python interpreter is usually installed as /usr/local/bin/python on
those machines where it is available; putting /usr/local/bin in your Unix
shell's search path makes it possible to start it by typing the command

python

to the shell. Since the choice of the directory where the interpreter lives is an
installation option, other places are possible; check with your local Python guru
or system administrator. (E.g., /usr/local/python is a popular alternative
location.)

the Python

installation

On Windows machines,
in
C:\Python26, though you can change this when you're running the installer. To
add this directory to your path, you can type the following command into the
command prompt in a DOS box:

is usually placed

set path=%path%;C:\python26

Typing an end-of-file character (Control-D on Unix, Control-Z on Windows)
at the primary prompt causes the interpreter to exit with a zero exit status. If that
doesn't work, you can exit the interpreter by typing the following commands:
import sys; sys.exit().

The interpreter's line-editing features usually aren't very sophisticated. On Unix,
whoever installed the interpreter may have enabled support for the GNU readline
library, which adds more elaborate interactive editing and history features.
Perhaps the quickest check to see whether command line editing is supported is
typing Control-P to the first Python prompt you get. If it beeps, you have command
line editing; see Appendix tut-interacting for an introduction to the keys. If nothing
appears to happen, or if ^P is echoed, command line editing isn't available; you'll

6

Tutorial de Python

only be able to use backspace to remove characters from the current line.

The interpreter operates somewhat like the Unix shell: when called with standard
input connected to a tty device, it reads and executes commands interactively;
when called with a file name argument or with a file as standard input, it reads
and executes a script from that file.

A second way of starting the interpreter is python -c command [arg] ...,
which executes the statement(s) in command, analogous to the shell's -c option.
Since Python statements often contain spaces or other characters that are
special
  • Links de descarga
http://lwp-l.com/pdf16531

Comentarios de: Tutorial de Python (0)


No hay comentarios
 

Comentar...

Nombre
Correo (no se visualiza en la web)
Valoración
Comentarios...
CerrarCerrar
CerrarCerrar
Cerrar

Tienes que ser un usuario registrado para poder insertar imágenes, archivos y/o videos.

Puedes registrarte o validarte desde aquí.

Codigo
Negrita
Subrayado
Tachado
Cursiva
Insertar enlace
Imagen externa
Emoticon
Tabular
Centrar
Titulo
Linea
Disminuir
Aumentar
Vista preliminar
sonreir
dientes
lengua
guiño
enfadado
confundido
llorar
avergonzado
sorprendido
triste
sol
estrella
jarra
camara
taza de cafe
email
beso
bombilla
amor
mal
bien
Es necesario revisar y aceptar las políticas de privacidad