Docsity
Docsity

Prepara tus exámenes
Prepara tus exámenes

Prepara tus exámenes y mejora tus resultados gracias a la gran cantidad de recursos disponibles en Docsity


Consigue puntos base para descargar
Consigue puntos base para descargar

Gana puntos ayudando a otros estudiantes o consíguelos activando un Plan Premium


Orientación Universidad
Orientación Universidad


Programación en Python: Conceptos Básicos, Diapositivas de Tecnologías de la Información y la Comunicación

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

2020/2021

Subido el 26/06/2022

spider-man-15
spider-man-15 🇪🇸

1 documento

1 / 59

Toggle sidebar

Esta página no es visible en la vista previa

¡No te pierdas las partes importantes!

bg1
The Zen of PythonThe Zen of Python
From the PEP 20 -- The Zen of Python:
Long time Pythoneer Tim Peters succinctly chan nels the BDFL's guiding principles for Python's design into 20 aphorisms, only 19 of w hich 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!
Python BasicsPython Basics
Math OperatorsMath Operators
From HighestHighest to LowestLowest precedence:
OperatorsOperators OperationOperation ExampleExample
** Exponent 2 ** 3 = 8
% Modulus/Remainder 22 % 8 = 6
// Integer division 22 // 8 = 2
/ Division 22 / 8 = 2.75
* Multiplication 3 * 3 = 9
- Subtraction 5 - 2 = 3
+ Addition 2 + 2 = 4
Examples of expressions in the interactive shell:
>>> 2 + 3 * 6
20
>>> (2 + 3) * 6
30
>>> 2 ** 8
256
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
pf22
pf23
pf24
pf25
pf26
pf27
pf28
pf29
pf2a
pf2b
pf2c
pf2d
pf2e
pf2f
pf30
pf31
pf32
pf33
pf34
pf35
pf36
pf37
pf38
pf39
pf3a
pf3b

Vista previa parcial del texto

¡Descarga Programación en Python: Conceptos Básicos y más Diapositivas en PDF de Tecnologías de la Información y la Comunicación solo en Docsity!

The Zen of PythonThe Zen of Python

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!

Python BasicsPython Basics

Math OperatorsMath Operators

From HighestHighest to LowestLowest precedence:

OperatorsOperators OperationOperation ExampleExample

** Exponent 2 ** 3 = 8

% Modulus/Remainder 22 % 8 = 6

// Integer division 22 // 8 = 2

/ Division 22 / 8 = 2.

* Multiplication 3 * 3 = 9

  • Subtraction 5 - 2 = 3

+ Addition 2 + 2 = 4

Examples of expressions in the interactive shell: >>> 2 + 3 * 6 20 >>> (2 + 3) * 6 30 >>> 2 ** 8 256

Data TypesData Types

Data TypeData Type ExamplesExamples

Integers -2, -1, 0, 1, 2, 3, 4, 5

Floating-point numbers -1.25, -1.0, --0.5, 0.0, 0.5, 1.0, 1.

Strings 'a', 'aa', 'aaa', 'Hello!', '11 cats'

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:

  1. It can be only one word.
  2. It can use only letters, numbers, and the underscore ( _ ) character.
  3. It can’t begin with a number.
  4. Variable name starting with an underscore ( _ ) are considered as "unuseful`. Example: >>> spam = 'Hello' >>> spam 'Hello' >>> _spam = 'Hello' _spam should not be used again in the code. CommentsComments Inline comment:

This is a comment

Multiline comment:

This is a

multiline comment

Float to Integer: >>> int(7.7) 7 >>> int(7.7) + 1 8

Flow ControlFlow Control

Comparison OperatorsComparison Operators

OperatorOperator MeaningMeaning

== Equal to

!= Not equal to

< Less than

> Greater Than

<= Less than or Equal to

>= Greater than or Equal to

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

Boolean evaluationBoolean evaluation

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.

The and Operator’s Truth Table:

ExpressionExpression Evaluates toEvaluates to

True and True True True and False False False and True False False and False False

The or Operator’s Truth Table:

ExpressionExpression Evaluates toEvaluates to

True or True True True or False True False or True True False or False False

The not Operator’s Truth Table:

ExpressionExpression Evaluates toEvaluates to

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)

The range() function can also be called with three arguments. The first two arguments will be the start and stop values, and the third will be the step argument. The

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

For else statementFor else statement

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")

Importing ModulesImporting Modules

import random for i in range(5): print(random.randint(1, 10)) import random, sys, os, math from random import *

Ending a Program Early with sys.exit()Ending a Program Early with sys.exit()

import sys while True: print('Type exit to exit.') response = input() if response == 'exit': sys.exit() print('You typed {}.'.format(response))

FunctionsFunctions

>>> def hello(name): >>> print('Hello {}'.format(name)) >>> >>> hello('Alice') >>> hello('Bob') Hello Alice Hello Bob

Return Values and return StatementsReturn Values and return Statements

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:

  1. If a variable is being used in the global scope (that is, outside of all functions), then it is always a global variable.
  2. If there is a global statement for that variable in a function, it is a global variable.
  3. Otherwise, if the variable is used in an assignment statement in the function, it is a local variable.
  4. But if the variable is not used in an assignment statement, it is a global variable.

Exception HandlingException Handling

Basic exception handlingBasic exception handling

>>> 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

Final code in exception handlingFinal code in exception handling

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 --

ListsLists

>>> 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

OperatorOperator EquivalentEquivalent

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']

Dictionaries and Structuring DataDictionaries and Structuring Data

Example Dictionary: myCat = {'size': 'fat', 'color': 'gray', 'disposition': 'loud'}

The keys(), values(), and items() MethodsThe keys(), values(), and items() Methods

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

Checking Whether a Key or Value Exists in a DictionaryChecking Whether a Key or Value Exists in a Dictionary

>>> 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}

set intersectionset intersection

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}

set differenceset difference

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}

set symetric_differenceset symetric_difference

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}

itertools Moduleitertools Module

The itertools module is a colection of tools intented to be fast and use memory efficiently when handling iterators (like lists or dictionaries).

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 itertools module comes in the standard library and must be imported.

The operator module will also be used. This module is not necessary when using itertools, but needed for some of the examples below.

accumulate()accumulate()

Makes an iterator that returns the results of a function. itertools.accumulate(iterable[, func]) Example: