



















































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
Una introducción a los conceptos básicos de la programación en python, incluyendo temas como comentarios, declaraciones continue, importación de módulos, el valor none, operadores de asignación aumentada, métodos de listas, conjuntos, iteradores y expresiones regulares. Se proporcionan ejemplos de código y explicaciones detalladas para ayudar a los estudiantes a comprender los fundamentos de la programación en python. El documento podría ser útil como material de estudio, resumen o referencia para cursos universitarios relacionados con la programación y el desarrollo de software.
Tipo: Diapositivas
1 / 59
Esta página no es visible en la vista previa
¡No te pierdas las partes importantes!




















































From the PEP 20 -- The Zen of Python: Long time Pythoneer Tim Peters succinctly channels the BDFL's guiding principles for Python's design into 20 aphorisms, only 19 of which have been written down. >>> 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!
From HighestHighest to LowestLowest precedence:
Examples of expressions in the interactive shell: >>> 2 + 3 * 6 20 >>> (2 + 3) * 6 30 >>> 2 ** 8 256
Data TypesData Types
String Concatenation and ReplicationString Concatenation and Replication String concatenation: >>> 'Alice' 'Bob' 'AliceBob' Note: Avoid + operator for string concatenation. Prefer string formatting. String Replication: >>> 'Alice' * 5 'AliceAliceAliceAliceAlice' VariablesVariables You can name a variable anything as long as it obeys the following rules:
Multiline comment:
Float to Integer: >>> int(7.7) 7 >>> int(7.7) + 1 8
These operators evaluate to True or False depending on the values you give them. Examples: >>> 42 == 42 True >>> 40 == 42 False >>> 'hello' == 'hello' True >>> 'hello' == 'Hello' False >>> 'dog' != 'cat' True >>> 42 == 42. True >>> 42 == '42' False
Never use == or != operator to evaluate boolean operation. Use the is or is not operators, or use implicit boolean evaluation. NO (even if they are valid Python): >>> True == True True
>>> True != False True YES (even if they are valid Python): >>> True is True True >>> True is not False True These statements are equivalent: >>> if a is True: >>> pass >>> if a is not False: >>> pass >>> if a: >>> pass And these as well: >>> if a is False: >>> pass >>> if a is not True: >>> pass >>> if not a: >>> pass Boolean OperatorsBoolean Operators There are three Boolean operators: and, or, and not.
True and True True True and False False False and True False False and False False
True or True True True or False True False or True True False or False False
not True False
spam = 0 while spam < 5: print('Hello, world.') spam = spam + 1 break Statementsbreak Statements If the execution reaches a break statement, it immediately exits the while loop’s clause: while True: print('Please type your name.') name = input() if name == 'your name': break print('Thank you!') continue Statementscontinue Statements When the program execution reaches a continue statement, the program execution immediately jumps back to the start of the loop. while True: print('Who are you?') name = input() if name != 'Joe': continue print('Hello, Joe. What is the password? (It is a fish.)') password = input() if password == 'swordfish': break print('Access granted.') for Loops and the range() Functionfor Loops and the range() Function >>> print('My name is') >>> for i in range(5): >>> print('Jimmy Five Times ({})'.format(str(i))) My name is Jimmy Five Times (0) Jimmy Five Times (1) Jimmy Five Times (2) Jimmy Five Times (3) Jimmy Five Times (4)
step is the amount that the variable is increased by after each iteration. >>> for i in range(0, 10, 2): >>> print(i) 0 2 4 6 8 You can even use a negative number for the step argument to make the for loop count down instead of up.
>>> for i in range(5, -1, -1): >>> print(i) 5 4 3 2 1 0
This allows to specify a statement to execute in case of the full loop has been executed. Only useful when a break condition can occur in the loop: >>> for i in [1, 2, 3, 4, 5]: >>> if i == 3: >>> break >>> else: >>> print("only executed when no item of the list is equal to 3")
import random for i in range(5): print(random.randint(1, 10)) import random, sys, os, math from random import *
import sys while True: print('Type exit to exit.') response = input() if response == 'exit': sys.exit() print('You typed {}.'.format(response))
>>> def hello(name): >>> print('Hello {}'.format(name)) >>> >>> hello('Alice') >>> hello('Bob') Hello Alice Hello Bob
When creating a function using the def statement, you can specify what the return value should be with a return statement. A return statement consists of the following: The return keyword. The value or expression that the function should return.
>>> def spam(): >>> global eggs >>> eggs = 'spam' >>> >>> eggs = 'global' >>> spam() >>> print(eggs) spam There are four rules to tell whether a variable is in a local scope or global scope:
>>> def spam(divideBy): >>> try: >>> return 42 / divideBy >>> except ZeroDivisionError as e: >>> print('Error: Invalid argument: {}'.format(e)) >>> >>> print(spam(2)) >>> print(spam(12)) >>> print(spam(0)) >>> print(spam(1))
Error: Invalid argument: division by zero None
Code inside the finally section is always executed, no matter if an exception has been raised or not, and even if an exception is not caught. >>> def spam(divideBy): >>> try: >>> return 42 / divideBy >>> except ZeroDivisionError as e: >>> print('Error: Invalid argument: {}'.format(e)) >>> finally: >>> print("-- division finished --") >>> print(spam(2)) -- division finished --
>>> print(spam(12)) -- division finished --
>>> print(spam(0)) Error: Invalid Argument division by zero -- division finished -- None >>> print(spam(1)) -- division finished --
>>> spam = ['cat', 'bat', 'rat', 'elephant'] >>> spam ['cat', 'bat', 'rat', 'elephant'] Getting Individual Values in a List with IndexesGetting Individual Values in a List with Indexes >>> spam = ['cat', 'bat', 'rat', 'elephant'] >>> spam[0] 'cat' >>> spam[1] 'bat' >>> spam[2] 'rat' >>> spam[3] 'elephant' Negative IndexesNegative Indexes >>> spam = ['cat', 'bat', 'rat', 'elephant'] >>> spam[-1] 'elephant' >>> spam[-3] 'bat' >>> 'The {} is afraid of the {}.'.format(spam[-1], spam[-3]) 'The elephant is afraid of the bat.' Getting Sublists with SlicesGetting Sublists with Slices >>> spam = ['cat', 'bat', 'rat', 'elephant'] >>> spam[0:4] ['cat', 'bat', 'rat', 'elephant'] >>> spam[1:3] ['bat', 'rat'] >>> spam[0:-1] ['cat', 'bat', 'rat'] >>> spam = ['cat', 'bat', 'rat', 'elephant'] >>> spam[:2] ['cat', 'bat'] >>> spam[1:] ['bat', 'rat', 'elephant'] Slicing the complete list will perform a copy:
>>> supplies = ['pens', 'staplers', 'flame-throwers', 'binders'] >>> for i, supply in enumerate(supplies): >>> print('Index {} in supplies is: {}'.format(str(i), supply)) Index 0 in supplies is: pens Index 1 in supplies is: staplers Index 2 in supplies is: flame-throwers Index 3 in supplies is: binders Looping Through Multiple Lists with zip()Looping Through Multiple Lists with zip() >>> name = ['Pete', 'John', 'Elizabeth'] >>> age = [6, 23, 44] >>> for n, a in zip(name, age): >>> print('{} is {} years old'.format(n, a)) Pete is 6 years old John is 23 years old Elizabeth is 44 years old The in and not in OperatorsThe in and not in Operators >>> 'howdy' in ['hello', 'hi', 'howdy', 'heyas'] True >>> spam = ['hello', 'hi', 'howdy', 'heyas'] >>> 'cat' in spam False >>> 'howdy' not in spam False >>> 'cat' not in spam True The Multiple Assignment TrickThe Multiple Assignment Trick The multiple assignment trick is a shortcut that lets you assign multiple variables with the values in a list in one line of code. So instead of doing this: >>> cat = ['fat', 'orange', 'loud'] >>> size = cat[0] >>> color = cat[1] >>> disposition = cat[2] You could type this line of code: >>> cat = ['fat', 'orange', 'loud'] >>> size, color, disposition = cat The multiple assignment trick can also be used to swap the values in two variables: >>> a, b = 'Alice', 'Bob' >>> a, b = b, a >>> print(a) 'Bob'
>>> print(b) 'Alice' Augmented Assignment OperatorsAugmented Assignment Operators
spam += 1 spam = spam + 1 spam -= 1 spam = spam - 1 spam *= 1 spam = spam * 1 spam /= 1 spam = spam / 1 spam %= 1 spam = spam % 1 Examples: >>> spam = 'Hello' >>> spam += ' world!' >>> spam 'Hello world!' >>> bacon = ['Zophie'] >>> bacon *= 3 >>> bacon ['Zophie', 'Zophie', 'Zophie'] Finding a Value in a List with the index() MethodFinding a Value in a List with the index() Method >>> spam = ['Zophie', 'Pooka', 'Fat-tail', 'Pooka'] >>> spam.index('Pooka') 1 Adding Values to Lists with the append() and insert() MethodsAdding Values to Lists with the append() and insert() Methods append()append(): >>> spam = ['cat', 'dog', 'bat'] >>> spam.append('moose') >>> spam ['cat', 'dog', 'bat', 'moose'] insert()insert(): >>> spam = ['cat', 'dog', 'bat'] >>> spam.insert(1, 'chicken') >>> spam ['cat', 'chicken', 'dog', 'bat'] Removing Values from Lists with remove()Removing Values from Lists with remove()
>>> list(('cat', 'dog', 5)) ['cat', 'dog', 5] >>> list('hello') ['h', 'e', 'l', 'l', 'o']
Example Dictionary: myCat = {'size': 'fat', 'color': 'gray', 'disposition': 'loud'}
values(): >>> spam = {'color': 'red', 'age': 42} >>> for v in spam.values(): >>> print(v) red 42 keys(): >>> for k in spam.keys(): >>> print(k) color age items(): >>> for i in spam.items(): >>> print(i) ('color', 'red') ('age', 42) Using the keys(), values(), and items() methods, a for loop can iterate over the keys, values, or key-value pairs in a dictionary, respectively. >>> spam = {'color': 'red', 'age': 42} >>> >>> for k, v in spam.items(): >>> print('Key: {} Value: {}'.format(k, str(v))) Key: age Value: 42 Key: color Value: red
>>> spam = {'name': 'Zophie', 'age': 7} >>> 'name' in spam.keys() True >>> 'Zophie' in spam.values() True
>>> # You can omit the call to keys() when checking for a key >>> 'color' in spam False >>> 'color' not in spam True The get() MethodThe get() Method Get has two parameters: key and default value if the key did not exist >>> picnic_items = {'apples': 5, 'cups': 2} >>> 'I am bringing {} cups.'.format(str(picnic_items.get('cups', 0))) 'I am bringing 2 cups.' >>> 'I am bringing {} eggs.'.format(str(picnic_items.get('eggs', 0))) 'I am bringing 0 eggs.' The setdefault() MethodThe setdefault() Method Let's consider this code: spam = {'name': 'Pooka', 'age': 5} if 'color' not in spam: spam['color'] = 'black' Using setdefault we could write the same code more succinctly: >>> spam = {'name': 'Pooka', 'age': 5} >>> spam.setdefault('color', 'black') 'black' >>> spam {'color': 'black', 'age': 5, 'name': 'Pooka'} >>> spam.setdefault('color', 'white') 'black' >>> spam {'color': 'black', 'age': 5, 'name': 'Pooka'} Pretty PrintingPretty Printing
>>> s = {} >>> type(s)
sets: unordered collections of unique elementssets: unordered collections of unique elements A set automatically remove all the duplicate values. >>> s = {1, 2, 3, 2, 3, 4} >>> s {1, 2, 3, 4} And as an unordered data type, they can't be indexed. >>> s = {1, 2, 3} >>> s[0] Traceback (most recent call last): File "", line 1, in TypeError: 'set' object does not support indexing >>> set add() and update()set add() and update() Using the add() method we can add a single element to the set. >>> s = {1, 2, 3} >>> s.add(4) >>> s {1, 2, 3, 4} And with update() , multiple ones. >>> s = {1, 2, 3} >>> s.update([2, 3, 4, 5, 6]) >>> s {1, 2, 3, 4, 5, 6} # remember, sets automatically remove duplicates set remove() and discard()set remove() and discard() Both methods will remove an element from the set, but remove() will raise a key error if the value doesn't exist. >>> s = {1, 2, 3} >>> s.remove(3) >>> s {1, 2} >>> s.remove(3) Traceback (most recent call last): File "", line 1, in KeyError: 3 discard() won't raise any errors. >>> s = {1, 2, 3} >>> s.discard(3) >>> s {1, 2} >>> s.discard(3) >>> set union()set union() union() or | will create a new set that contains all the elements from the sets provided.
>>> s1 = {1, 2, 3} >>> s2 = {3, 4, 5} >>> s1.union(s2) # or 's1 | s2' {1, 2, 3, 4, 5}
intersection or & will return a set containing only the elements that are common to all of them. >>> s1 = {1, 2, 3} >>> s2 = {2, 3, 4} >>> s3 = {3, 4, 5} >>> s1.intersection(s2, s3) # or 's1 & s2 & s3' {3}
difference or - will return only the elements that are unique to the first set (invoked set). >>> s1 = {1, 2, 3} >>> s2 = {2, 3, 4} >>> s1.difference(s2) # or 's1 - s2' {1} >>> s2.difference(s1) # or 's2 - s1' {4}
symetric_difference or ^ will return all the elements that are not common between them. >>> s1 = {1, 2, 3} >>> s2 = {2, 3, 4} >>> s1.symmetric_difference(s2) # or 's1 ^ s2' {1, 4}
From the official Python 3.x documentation: The module standardizes a core set of fast, memory efficient tools that are useful by themselves or in combination. Together, they form an “iterator algebra” making it possible to construct specialized tools succinctly and efficiently in pure Python.
The operator module will also be used. This module is not necessary when using itertools, but needed for some of the examples below.
Makes an iterator that returns the results of a function. itertools.accumulate(iterable[, func]) Example: