

























































































Prepara tus exámenes y mejora tus resultados gracias a la gran cantidad de recursos disponibles en Docsity
Gana puntos ayudando a otros estudiantes o consíguelos activando un Plan Premium
Prepara tus exámenes
Prepara tus exámenes y mejora tus resultados gracias a la gran cantidad de recursos disponibles en Docsity
Prepara tus exámenes con los documentos que comparten otros estudiantes como tú en Docsity
Encuentra los documentos específicos para los exámenes de tu universidad
Estudia con lecciones y exámenes resueltos basados en los programas académicos de las mejores universidades
Responde a preguntas de exámenes reales y pon a prueba tu preparación
Consigue puntos base para descargar
Gana puntos ayudando a otros estudiantes o consíguelos activando un Plan Premium
Comunidad
Pide ayuda a la comunidad y resuelve tus dudas de estudio
Ebooks gratuitos
Descarga nuestras guías gratuitas sobre técnicas de estudio, métodos para controlar la ansiedad y consejos para la tesis preparadas por los tutores de Docsity
APRENDER A PROGRAMAR CON PYTHON.
Tipo: Guías, Proyectos, Investigaciones
1 / 97
Esta página no es visible en la vista previa
¡No te pierdas las partes importantes!


























































































Materiales del curso de programación en Python - Nivel básico, Publicación 0.
Esta es la documentación para el capacitación “Programación en Python - Nivel básico”.
Sobre esta capacitación Para dominar Python se tiene pensado como un entrenamiento de 2 a 3 días para las personas que son nuevas en Python o los que quieren aprender acerca de las actuales mejores prácticas del desarrollo en Python. La planificación de este capacitación se estima en: Una capacitación de nivel básico (2 a 3 días) que cubre los diez (10) capítulos.
Tabla de contenidos:
Índice general 1
Materiales del curso de programación en Python - Nivel básico, Publicación 0.
2 Índice general
Materiales del curso de programación en Python - Nivel básico, Publicación 0.
Comunidad Python Argentina^12.
Vídeo tutorial
Tutorial Python 1 - Introducción al Lenguaje de Programación^13.
(^12) http://www.python.org.ar/ (^13) https://www.youtube.com/watch?v=CjmzDHMHxwU
4 Capítulo 1. Introducción a Python
CAPÍTULO 2
Instalando Python
Instalando Python en Windows^1. Instalando Python en una Mac^2.
Recursos de Descargas de Python
Descarga Python^3. PyPI - the Python Package Index^4.
Vídeo tutorial
Tutorial Python 2 - Instalación^5.
(^1) https://www.youtube.com/watch?v=VTykmP-a2KY (^2) http://es.wikibooks.org/wiki/Inmersi %C3 %B3n_en_Python/Instalaci %C3 %B3n_de_Python/Python_en_Mac_OS_X (^3) https://www.python.org/downloads/ (^4) https://pypi.python.org/pypiorg/wiki/Inmersi %C3 %B3n_en_Python/Instalaci %C3 %B3n_de_Python/Python_en_Mac_OS_X (^5) https://www.youtube.com/watch?v=VTykmP-a2KY
CAPÍTULO 3
Inmersión al modo interactivo de Python
Sobre este artículo Autor(es) Leonardo J. Caballero G. Correo(s) [email protected] Compatible con Python 2.4 o versiones superiores Fecha 31 de Diciembre de 2013 [email protected]
Descripción general
Este articulo se basa en el documento Una pequeña inmersión al modo interactivo de Python^1 generado por la fundación Cenditel^2 y la idea principal de este tutorial es para alguien que NUNCA ha trabajando con el interprete de Python^3 pueda tener un primer acercamiento SIN PROGRAMAR, solamente con conocer el uso del interprete y sus comandos básicos.
Características de Python
Es un lenguaje de programación multiparadigma^4. Soporta orientación a objetos^5 , programación imperativa^6 y, en menor medida, programación funcional^7. Es un lenguaje interpretado^8 , usa tipado dinámico^9 , es fuertemente tipado^10 y es multiplataforma^11.
Introspección en Python
Según el libro Inmersión en Python ...Como usted sabe, todo en Python es un objeto^12 , y la introspección es código que examina como objetos otros módulos y funciones en memoria, obtiene información sobre ellos y los maneja.
(^1) http://plataforma.cenditel.gob.ve/wiki/Plone %3AUnaPequenaInmersionPython (^2) https://twitter.com/cenditel (^3) http://www.python.org/ (^4) http://es.wikipedia.org/wiki/Lenguaje_de_programaci %C3 %B3n_multiparadigma (^5) http://es.wikipedia.org/wiki/Programaci %C3 %B3n_orientada_a_objetos (^6) http://es.wikipedia.org/wiki/Programaci %C3 %B3n_imperativa (^7) http://es.wikipedia.org/wiki/Programaci %C3 %B3n_funcional (^8) http://es.wikipedia.org/wiki/Lenguaje_interpretado (^9) http://es.wikipedia.org/wiki/Tipado_din %C3 %A1mico (^10) http://es.wikipedia.org/wiki/Lenguaje_de_programaci %C3 %B3n_fuertemente_tipado (^11) http://es.wikipedia.org/wiki/Multiplataforma (^12) http://es.diveintopython.org/odbchelper_objects.html
Materiales del curso de programación en Python - Nivel básico, Publicación 0.
De paso, usted podrá definir las funciones sin nombre, las llamará a funciones con argumentos sin orden, y podrá hacer referencia a funciones cuyos nombres desconocemos.
Es importante conocer Python a través de su interprete debido a varios factores:
Conocer las clases, sus funciones y atributos propios, a través de la introspección del lenguaje. Disponibilidad de consultar la documentación del lenguaje desde el interprete, por mucho tiempo no estaba disponible documentación tipo Javadoc^13 o diagramas de clases^14 del propio lenguaje por lo cual muchas programadores Python se acostumbraron a estudiar su código de esta forma, así que le recomiendo que use el interprete python para eso. Hoy en día existente herramientas que te permiten generar documentación desde los códigos fuentes Python como Sphinx^15.
La forma mas fácil es iniciar tu relación con Python simplemente ejecutando el comando python de la siguiente forma:
$ python Python 2.5.2 (r252:60911, Jan 4 2009, 17:40:26) [GCC 4.3.2] on linux Type "help", "copyright", "credits" or "license" for more information. >>>
Pidiendo la ayudar del interprete de Python
>>> help Type help() for interactive help, or help(object) for help about object. >>> help()
Welcome to Python 2.5! 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://www.python.org/doc/tut/.
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>
Para ejecutar la ayuda disponible sobre la sintaxis Python ejecute el siguiente comando:
help> modules
Please wait a moment while I gather a list of all available modules...
/usr/lib/python2.5/site-packages/apt/init.py:18: FutureWarning: apt API not stable yet warnings.warn("apt API not stable yet", FutureWarning) Data Dir: /usr/share/colorblind (^13) http://es.wikipedia.org/wiki/Javadoc (^14) http://es.wikipedia.org/wiki/Diagrama_de_clases (^15) http://en.wikipedia.org/wiki/Sphinx_ %28documentation_generator %
8 Capítulo 3. Inmersión al modo interactivo de Python
Materiales del curso de programación en Python - Nivel básico, Publicación 0.
ImageColor audioop ipy_completers signal ImageDraw base64 ipy_constants site ImageDraw2 bdb ipy_defaults sitecustomize ImageEnhance binascii ipy_editors smtpd ImageFile binhex ipy_exportdb smtplib ImageFileIO bisect ipy_extutil sndhdr ImageFilter bonobo ipy_fsops socket ImageFont brlapi ipy_gnuglobal spwd ImageGL bsddb ipy_greedycompleter sqlite ImageGrab bugbuddy ipy_jot sqlobject ImageMath bz2 ipy_kitcfg sre ImageMode cPickle ipy_legacy sre_compile ImageOps cProfile ipy_leo sre_constants ImagePalette cStringIO ipy_lookfor sre_parse ImagePath cairo ipy_p4 stat ImageQt calendar ipy_profile_doctest statvfs ImageSequence cgi ipy_profile_none string ImageStat cgitb ipy_profile_scipy stringold ImageTransform chunk ipy_profile_sh stringprep ImageWin clearcmd ipy_profile_zope strop ImtImagePlugin cmath ipy_pydb struct InterpreterExec cmd ipy_rehashdir subprocess InterpreterPasteInput code ipy_render sunau IptcImagePlugin codecs ipy_server sunaudio JpegImagePlugin codeop ipy_signals svn McIdasImagePlugin collections ipy_stock_completers symbol MicImagePlugin colorblind ipy_system_conf symtable MimeWriter colorsys ipy_traits_completer sys MpegImagePlugin commands ipy_vimserver syslog MspImagePlugin compileall ipy_which tabnanny MySQLdb compiler ipy_winpdb tarfile Numeric configobj ipy_workdir telnetlib Numeric_headers constants itertools tempfile ORBit contextlib jobctrl templatetags OggConvert cookielib keyword terminatorlib OleFileIO copy ldap termios PIL copy_reg ldapurl test PSDraw crypt ldif textwrap PaletteFile csv ledit this PalmImagePlugin ctypes libsvn thread PcdImagePlugin cups libxml2 threading PcfFontFile cupsext libxml2mod time PcxImagePlugin cupsutils linecache timeit PdfImagePlugin curses linuxaudiodev tkColorChooser PhysicalQInput datetime locale tkCommonDialog PhysicalQInteractive dbhash logging tkFileDialog PixarImagePlugin dbm macpath tkFont PngImagePlugin dbus macurl2path
10 Capítulo 3. Inmersión al modo interactivo de Python
Materiales del curso de programación en Python - Nivel básico, Publicación 0.
tkMessageBox PpmImagePlugin dbus_bindings mailbox tkSimpleDialog Precision debconf mailcap toaiff PsdImagePlugin decimal markupbase token Queue deskbar marshal tokenize ScrolledText difflib math totem SgiImagePlugin dircache md5 trace SimpleDialog dis mediaprofiles traceback SimpleHTTPServer distutils metacity tty SimpleXMLRPCServer django mhlib turtle SocketServer doctest mimetools types SpiderImagePlugin drv_libxml2 mimetypes umath StringIO dsextras mimify unicodedata SunImagePlugin dsml mmap unittest TYPES dumbdbm modulefinder uno TarIO dummy_thread multiarray unohelper TgaImagePlugin dummy_threading multifile urllib TiffImagePlugin easy_install mutex urllib TiffTags egg nautilusburn urlparse Tix email netrc user Tkconstants encodings new uu Tkdnd envbuilder nis uuid Tkinter envpersist nntplib validate UserArray errno ntpath virtualenv UserDict evolution nturl2path virtualenv_support UserList exceptions numeric_formats vte UserString ext_rescapture numeric_version warnings WalImageFile fcntl opcode wave WmfImagePlugin fdpexpect operator weakref XVThumbImagePlugin filecmp optparse webbrowser XbmImagePlugin fileinput orca whichdb XpmImagePlugin fnmatch os win32clip _LWPCookieJar foomatic os2emxpath wnck _MozillaCookieJar formatter ossaudiodev wsgiref builtin formencode pango xdg future fpformat pangocairo xdrlib _ast ftplib parser xml _bisect functools pcardext xmllib _bsddb gc pdb xmlrpclib _codecs gconf pexpect xxsubtype _codecs_cn gda pickle z3c _codecs_hk gdata pickleshare zc _codecs_iso2022 gdbm pickletools zipfile _codecs_jp gdl pip zipimport _codecs_kr getopt pipes zlib _codecs_tw getpass pkg_resources zopeskel _csv gettext pkgutil
Enter any module name to get more help. Or, type "modules spam" to search for modules whose descriptions contain the word "spam".
help> os Help on module os:
3.3. Introspección en Python 11
Materiales del curso de programación en Python - Nivel básico, Publicación 0.
'chroot', 'close', 'confstr', 'confstr_names', 'ctermid', 'curdir', 'defpath', 'devnull', 'dup', 'dup2', 'environ', 'errno', 'error', 'execl', 'execle', 'execlp', 'execlpe', 'execv', 'execve', 'execvp', 'execvpe', 'extsep', 'fchdir', 'fdatasync', 'fdopen', 'fork', 'forkpty', 'fpathconf', 'fstat', 'fstatvfs', 'fsync', 'ftruncate', 'getcwd', 'getcwdu', 'getegid', 'getenv', 'geteuid', 'getgid', 'getgroups', 'getloadavg', 'getlogin', 'getpgid', 'getpgrp', 'getpid', 'getppid', 'getsid', 'getuid', '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', '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'] >>>
Otro ejemplo de uso, es poder usar el método file para determinar la ubicación de la librería importada de la siguiente forma:
>>> os.file '/usr/lib/python2.5/os.pyc' >>>
También puede consultar la documentación de la librería os ejecutando el siguiente comando:
>>> os.doc "OS routines for Mac, NT, or Posix depending on what system we're on.\n\nThis exports:\n - all functions from posix, nt, os2, mac, or ce, e.g. unlink, stat, etc.\n - os.path is one of the modules posixpath, ntpath, or macpath\n - os.name is 'posix', 'nt', 'os2', 'mac', 'ce' or 'riscos'\n - os.curdir is a string representing the current directory ('.' or ':')\n - os.pardir is a string representing the parent directory ('..' or '::')\n - os.sep is the (or a most common) pathname separator ('/' or ':' or '\\')\n - os.extsep is the extension separator ('.' or '/')\n - os.altsep is the alternate pathname separator (None or '/')\n
Ejecute el comando exit() para salir del interprete...
>>> exit()
Para mejorar la experiencia con el interprete Python le sugerimos instalar el programa IPython, según su docu- mentación:
3.3. Introspección en Python 13
Materiales del curso de programación en Python - Nivel básico, Publicación 0.
Según Wikipedia
“IPython es un shell interactivo que añade funcionalidades extra al modo interactivo^17 incluido con Python, como resaltado de líneas y errores mediante colores, una sintaxis adicional para el shell, autocompletado mediante tabulador de variables, módulos y atributos; entre otras funcionalidades. Es un componente del paquete SciPy^18 .”
Para mayor información visite su página principal de ipython^19 y si necesita instalar este programa ejecute el siguiente comando:
Luego cierra sesión de root y vuelve al usuario y sustituya el comando python por ipython de la siguiente forma:
$ ipython Python 2.5.2 (r252:60911, Jan 24 2010, 17:44:40) Type "copyright", "credits" or "license" for more information.
IPython 0.8.4 -- An enhanced Interactive Python. ? -> Introduction and overview of IPython's features. %quickref -> Quick reference. help -> Python's own help system. object? -> Details about 'object'. ?object also works, ?? prints more.
In [ 1 ]:
Un ejemplo de uso del comando help es consultar la ayuda del comando dir y se ejecuta de la siguiente forma:
In [ 1 ]: help(dir) Help on built- in function dir in module builtin:
dir(...) dir([object]) -> list of strings
Return an alphabetized list of names comprising (some of) the attributes of the given object, and of attributes reachable from it :
No argument: the names in the current scope. Module object: the module attributes. Type or class object : its attributes, and recursively the attributes of its bases. Otherwise: its attributes, its class's attributes, and recursively the attributes of its class's base classes.
Entonces presione la tecla q para salir de la ayuda
De nuevo realice la importación de la librería del estándar Python llamada os
In [ 2 ]: import os
También consultar los detalles acerca del ‘objeto’ para esto use como ejemplo la librería os ejecutando el siguiente comando:
In [2]: os? Type: module Base Class: String Form: Namespace: Interactive
(^17) http://es.wikipedia.org/wiki/Python#Modo_interactivo (^18) http://en.wikipedia.org/wiki/SciPy (^19) http://ipython.scipy.org/
14 Capítulo 3. Inmersión al modo interactivo de Python