SlideShare a Scribd company logo
1 of 54
Download to read offline
Beautiful Python
@alipeji | alicia@stylesage.co
¡Hola!
@alipeji | alicia@stylesage.co
El outfit perfecto
para un código pythonico
La ropa interior
tipos básicos
@stylishcurves
Strings
# Cadenas muy largas
my_very_big_string = 'For a long time I used to go to bed early. ' + 
'Sometimes, when I had put out my candle, my eyes would close ' + 
'so quickly that I had not even time to say Im going to sleep.'
my_very_big_string = '''For a long time I used to go to bed early.
Sometimes, when I had put out my candle, my eyes would close
so quickly that I had not even time to say Im going to sleep.'''
my_very_big_string = ('For a long time I used to go to bed early. '
'Sometimes, when I had put out my candle, my eyes would close '
'so quickly that I had not even time to say Im going to sleep.')
if stylesage.find('Fashion') != -1:
pass
# Comprobar si una cadena contiene otra
stylesage = 'Fashion meets Big Data'
if 'Fashion' in stylesage:
pass
>>> name = 'Alicia'
>>> cats = 2
>>> print('My name is ' + name + ' and I have ' + str(cats) + ' cats')
# Usa String Formatting!!
#1 – “Old Style”
>>> name = 'Bob'
>>> 'Hello, %s' % name
'Hello, Bob'
# String Formatting
#2 – “New Style” String Formatting
>>> name = 'Bob'
>>> 'Hello, {}'.format(name)
'Hello, Bob'
#3 – Literal String Interpolation
# (Python 3.6+)
>>> name = 'Bob'
>>> f'Hello, {name}'
'Hello, Bob'
#4 – Template Strings
>>> from string import Template
>>> t = Template('Hello, $name!')
>>> t.substitute(name='Bob')
'Hello, Bob!'
Booleanos
>>> if x >= start and x <= end:
>>> pass
>>> if len(items) != 0:
>>> pass
>>> if lang == 'Spanish':
... welcome = 'Bienvenido'
... else:
... welcome = 'Welcome'
>>> if start <= x <= end:
>>> pass
>>> if items:
>>> pass
>>> welcome = 'Bienvenido' 
... if lang == 'Spanish' else 'Welcome'
Truth Value Testing
Los siguientes valores serán evaluados como False en una comparación:
● None
● False
● Cero en cualquier tipo numérico, por ejemplo: 0, 0L, 0.0, 0j
● Cualquier secuencia vacía, por ejemplo: '', (), []
● Los diccionarios vacíos: {}
● Las instancias de cualquier clase, si esta define los métodos __nonzero__() o __len__(),
cuando estos métodos devuelven cero o False
En cualquier otro caso, serán evaluados como True
>>> values = [True, True, False, False]
>>> i = 0
>>> flag = False
>>> while not flag and i < len(values):
... flag = values[i]
... i += 1
>>> flag
False
>>> any(values)
True
# ¿algún True en la lista?
>>> all(values)
False
>>> values = range(10) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> i = 0
>>> flag = False
>>> while not flag and i < len(values):
... flag = (values[i] == 0)
... i += 1
>>> flag
True
>>> any(values)
True
# ¿algún 0 en la lista?
>>> all(values)
False
Variables
>>> b, a = a, b>>> temp = a
>>> a = b
>>> b = temp
>>> l = ['David', 'Pythonista', '555-55-55']
>>> name = l[0]
>>> title = l[1]
>>> phone = l[2]
>>> name, title, phone = l
>>> name, _, phone = l
Los básicos
colecciones
Tuplas
# Crear una tupla
>>> arr = 'one', 'two', 'three'
>>> arr[0]
'One'
# Son immutables:
>>> arr[1] = 'hello'
TypeError:
"'tuple' object does not support
item assignment"
>>> del arr[1]
TypeError:
"'tuple' object doesn't support item
deletion"
# Soportan múltiples
# tipos de datos:
>>> arr + (23,)
('one', 'two', 'three', 23)
# namedtuples
>>> from collections 
... import namedtuple
>>> Car = namedtuple('Car', 
... 'color mileage automatic')
>>> car1 = Car('red', 3812.4, True)
# Acceder a los campos:
>>> car1.color
'red'
>>> car1.mileage
3812.4
>>> car1.automatic
True
# Los campos son inmutables:
>>> car1.mileage = 12
AttributeError: "can't set attribute"
Listas
# Crear una lista
>>> arr = ['one', 'two', 'three']
>>> arr[0]
'One'
# Son mutables:
>>> arr[1] = 'hello'
>>> arr
['one', 'hello', 'three']
>>> del arr[1]
>>> arr
['one', 'three']
# Soportan múltiples tipos:
>>> arr.append(23)
>>> arr
['one', 'three', 23]
# array slicing
a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> a[-1]
10
>>> a[2:8]
[2, 3, 4, 5, 6, 7]
>>> a[:5]
[0, 1, 2, 3, 4]
>>> a[5:]
[5, 6, 7, 8, 9, 10]
>>> a[2:8:2]
[2, 4, 6]
>>> a[::2]
[0, 2, 4, 6, 8, 10]
>>> a = [1, 2, 3, 4, 5]
>>> a[2:4] = [0, 0, 0]
>>> a
[1, 2, 0, 0, 0, 5]
Sets
>>> A = {1, 2, 3, 3}
>>> B = {3, 4, 5, 6, 7}
>>> A
set([1, 2, 3])
>>> B
set([3, 4, 5, 6, 7])
>>> A | B
set([1, 2, 3, 4, 5, 6, 7])
>>> A & B
set([3])
>>> A - B
set([1, 2])
>>> A ^ B
set([1, 2, 4, 5, 6, 7])
>>> A
Counter({2: 2, 1: 1})
>>> B
Counter({2: 2, 3: 1})
>>> C.most_common()
[(3, 4), (1, 2), (2, 2), (4, 1), (5, 1),
(6, 1), (7, 1)]
>>> C.most_common(1)
[(3, 4)]
>>> C.most_common(3)
[(3, 4), (1, 2), (2, 2)]
>>> A = collections.Counter([1, 2, 2])
>>> B = collections.Counter([2, 2, 3])
>>> C = collections.Counter([1, 1, 2, 2, 3, 3, 3, 3, 4, 5, 6, 7])
>>> A | B
Counter({2: 2, 1: 1, 3: 1})
>>> A & B
Counter({2: 2})
>>> A + B
Counter({2: 4, 1: 1, 3: 1})
Bucles “pythonicos”
>>> a = ['Hello', 'world', '!']
>>> for i, x in enumerate(a):
... print '{}: {}'.format(i, x)
>>> a = ['Hello', 'world', '!']
>>> i = 0
>>> for x in a:
... print '{}: {}'.format(i, x)
... i += 1
# Imprimir los elementos de una lista y su índice
>>> squares = [x * x for x in range(10)]>>> even_squares = []
>>> for x in range(10):
... even_squares.append(x * x)
>>> even_squares = []
>>> for x in range(10):
... if x % 2 == 0:
... even_squares.append(x * x)
>>> even_squares = [x * x for x in range(10) 
... if x % 2 == 0]
# Obtener todos los cuadrados de los números del 0 al 9
# Obtener todos los cuadrados de los números pares del 0 al 9
>>> zip(names, surnames)
[('John', 'Cleese'), ('Eric', 'Idle'),
('Terry', 'Gilliam')]
>>> names = ['John', 'Eric', 'Terry']
>>> surnames = ['Cleese', 'Idle', 'Gilliam']
>>> people = []
>>> for i in range(len(names)):
... people.append((names[i], surnames[i]))
>>> print(people)
[('John', 'Cleese'), ('Eric', 'Idle'),
('Terry', 'Gilliam')]
# Obtener en una sola lista los pares nombre-apellido
Generadores
>>> squares = (i*i for i in xrange(1000000))
>>> next(squares)
0
>>> next(squares)
1
>>> next(squares)
4
>>> next(squares)
9
>>> next(squares)
16
>>> from collections import deque
>>> q = deque(squares)
>>> q.pop()
999998000001
>>> q.pop()
999996000004
>>> q.popleft()
0
>>> q.popleft()
1
>>> squares = [i*i for i in range(1000000)]
# Add to the right
>>> d = collections.deque()
>>> d.extend([0, 1, 2, 3, 4])
deque([0, 1, 2, 3, 4])
>>> d.append(5)
deque([0, 1, 2, 3, 4, 5])
# Add to the left
>>> d = collections.deque()
>>> d.extendleft([0, 1, 2, 3, 4])
deque([4, 3, 2, 1, 0])
>>> d.appendleft(5)
deque([5, 4, 3, 2, 1, 0])
>>> last_three = collections.deque(maxlen=3)
>>> for i in xrange(5):
... last_three.append(i)
... print ', '.join(
... str(x) for x in last_three)
0
0, 1
0, 1, 2
1, 2, 3
2, 3, 4
La “pieza luz”
diccionarios
Valores por defecto
>>> name_for_userid = {
... 382: 'Alice',
... 950: 'Bob',
... 590: 'Dilbert',
... }
>>> def greeting(userid):
... if userid in name_for_userid:
... return 'Hi %s!' % name_for_userid[userid]
... else:
... return 'Hi there!'
>>> def greeting(userid):
... try:
... return 'Hi %s!' % name_for_userid[userid]
... except KeyError:
... return 'Hi there'
>>> def greeting(userid):
... return 'Hi %s!' % user_dict.get(userid, 'there')
>>> visits = {
... 'Alice': 0,
... 'Bob': 0,
... 'Dilbert': 0,
... }
>>> def add_visit(user):
... if user not in visits:
... visits[user] = 0
... visits[user] += 1
>>> def add_visit(user):
... visits.setdefault(user, 0)
... visits[user] += 1
>>> def add_visit(user):
... visits[user] = visits.get(user, 0) + 1
>>> visits = defaultdict(int)
>>> def add_visit(user):
... visits[user] += 1
Comprensión
>>> m = {x: x ** 2 for x in range(5)}
>>> m
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
>>> m = {x: 'A' + str(x) for x in range(5)}
>>> m
{0: 'A0', 1: 'A1', 2: 'A2', 3: 'A3', 4: 'A4', 5}
>>> # Invertir las clave-valor
>>> m = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
>>> {v: k for k, v in m.items()}
{1: 'a', 2: 'b', 3: 'c', 4: 'd'}
Complementos
Parámetros (args & kwargs)
# * args
>>> def test_var_args(f_arg, *argv):
... print "first normal arg:", f_arg
... for arg in argv:
... print "another arg through *argv :", arg
>>> test_var_args()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: test_var_args() takes at least 1 argument (0 given)
>>> test_var_args('yasoob', 'python', 'eggs', 'test')
'first normal arg: yasoob'
'another arg through *argv : python'
'another arg through *argv : eggs'
'another arg through *argv : test'
# ** kargs
>>> def greet_me(**kwargs):
... for key, value in kwargs.iteritems():
... print "%s == %s" %(key,value)
>>> greet_me(name="yasoob")
'name == yasoob'
>>> kwargs = {"arg3": 3, "arg2": "two", "arg1":5}
>>> greet_me(**kwargs)
'arg1 == 5'
'arg2 == two'
'arg3 == 3'
Asserts
>>> def apply_discount(product, discount):
... price = int(product['price'] * (1.0 - discount))
... assert 0 <= price <= product['price']
... return price
>>> shoes = {'name': 'Fancy Shoes', 'price': 14900}
>>> apply_discount(shoes, 0.25)
11175
>>> apply_discount(shoes, 2.0)
Traceback (most recent call last):
File "<input>", line 1, in <module>
apply_discount(prod, 2.0)
File "<input>", line 4, in
apply_discount
assert 0 <= price <= product['price']
AssertionError
# internamente un assert es...
>>> if __debug__:
... if not expression1:
... raise AssertionError(expression2)
# por eso nunca hay que hacer...
>>> def delete_product(prod_id, user):
>>> assert user.is_admin(), 'Comprueba si es administrador'
>>> assert store.has_product(prod_id), 'Comprueba si existe'
>>> store.get_product(prod_id).delete()
Contextos
// WARNING!! Código Java en una charla Python!!
void muestraContenido(String archivo) throws FileNotFoundException, IOException {
String cadena;
FileReader f = new FileReader(archivo);
BufferedReader b = new BufferedReader(f);
while((cadena = b.readLine())!=null) {
System.out.println(cadena);
}
b.close();
}
with open(fname, 'r') as file_in:
print file_in.read()
class File():
def __init__(self, filename, mode):
self.filename = filename
self.mode = mode
def __enter__(self):
self.open_file = open(self.filename, self.mode)
return self.open_file
def __exit__(self, *args):
self.open_file.close()
Referencias Python Tricks: The Book
A Buffet of Awesome Python Features
30 Python Language Features and Tricks
You May Not Know About
PYTHON TIPS web
¡Gracias!
@alipeji | alicia@stylesage.co

More Related Content

What's hot

Exhibition of Atrocity
Exhibition of AtrocityExhibition of Atrocity
Exhibition of AtrocityMichael Pirnat
 
Groovy puzzlers по русски с Joker 2014
Groovy puzzlers по русски с Joker 2014Groovy puzzlers по русски с Joker 2014
Groovy puzzlers по русски с Joker 2014Baruch Sadogursky
 
Introduction to Python
Introduction to PythonIntroduction to Python
Introduction to PythonUC San Diego
 
A limited guide to intermediate and advanced Ruby
A limited guide to intermediate and advanced RubyA limited guide to intermediate and advanced Ruby
A limited guide to intermediate and advanced RubyVysakh Sreenivasan
 
Swift에서 꼬리재귀 사용기 (Tail Recursion)
Swift에서 꼬리재귀 사용기 (Tail Recursion)Swift에서 꼬리재귀 사용기 (Tail Recursion)
Swift에서 꼬리재귀 사용기 (Tail Recursion)진성 오
 
Advanced Python, Part 2
Advanced Python, Part 2Advanced Python, Part 2
Advanced Python, Part 2Zaar Hai
 
Lecture on Rubinius for Compiler Construction at University of Twente
Lecture on Rubinius for Compiler Construction at University of TwenteLecture on Rubinius for Compiler Construction at University of Twente
Lecture on Rubinius for Compiler Construction at University of TwenteDirkjan Bussink
 
TDC2017 | São Paulo - Trilha Programação Funcional How we figured out we had ...
TDC2017 | São Paulo - Trilha Programação Funcional How we figured out we had ...TDC2017 | São Paulo - Trilha Programação Funcional How we figured out we had ...
TDC2017 | São Paulo - Trilha Programação Funcional How we figured out we had ...tdc-globalcode
 
Python tutorial
Python tutorialPython tutorial
Python tutorialRajiv Risi
 
Py Die R E A D M E
Py Die  R E A D M EPy Die  R E A D M E
Py Die R E A D M Ecfministries
 
From Java to Kotlin beyond alt+shift+cmd+k - Kotlin Community Conf Milan
From Java to Kotlin beyond alt+shift+cmd+k - Kotlin Community Conf MilanFrom Java to Kotlin beyond alt+shift+cmd+k - Kotlin Community Conf Milan
From Java to Kotlin beyond alt+shift+cmd+k - Kotlin Community Conf MilanFabio Collini
 
Kotlin Basics - Apalon Kotlin Sprint Part 2
Kotlin Basics - Apalon Kotlin Sprint Part 2Kotlin Basics - Apalon Kotlin Sprint Part 2
Kotlin Basics - Apalon Kotlin Sprint Part 2Kirill Rozov
 
From java to kotlin beyond alt+shift+cmd+k - Droidcon italy
From java to kotlin beyond alt+shift+cmd+k - Droidcon italyFrom java to kotlin beyond alt+shift+cmd+k - Droidcon italy
From java to kotlin beyond alt+shift+cmd+k - Droidcon italyFabio Collini
 

What's hot (20)

Exhibition of Atrocity
Exhibition of AtrocityExhibition of Atrocity
Exhibition of Atrocity
 
Groovy puzzlers по русски с Joker 2014
Groovy puzzlers по русски с Joker 2014Groovy puzzlers по русски с Joker 2014
Groovy puzzlers по русски с Joker 2014
 
Introduction to Python
Introduction to PythonIntroduction to Python
Introduction to Python
 
A limited guide to intermediate and advanced Ruby
A limited guide to intermediate and advanced RubyA limited guide to intermediate and advanced Ruby
A limited guide to intermediate and advanced Ruby
 
Swift에서 꼬리재귀 사용기 (Tail Recursion)
Swift에서 꼬리재귀 사용기 (Tail Recursion)Swift에서 꼬리재귀 사용기 (Tail Recursion)
Swift에서 꼬리재귀 사용기 (Tail Recursion)
 
Advanced Python, Part 2
Advanced Python, Part 2Advanced Python, Part 2
Advanced Python, Part 2
 
Lecture on Rubinius for Compiler Construction at University of Twente
Lecture on Rubinius for Compiler Construction at University of TwenteLecture on Rubinius for Compiler Construction at University of Twente
Lecture on Rubinius for Compiler Construction at University of Twente
 
Introduction to Groovy
Introduction to GroovyIntroduction to Groovy
Introduction to Groovy
 
Pooya Khaloo Presentation on IWMC 2015
Pooya Khaloo Presentation on IWMC 2015Pooya Khaloo Presentation on IWMC 2015
Pooya Khaloo Presentation on IWMC 2015
 
SDC - Einführung in Scala
SDC - Einführung in ScalaSDC - Einführung in Scala
SDC - Einführung in Scala
 
Benefits of Kotlin
Benefits of KotlinBenefits of Kotlin
Benefits of Kotlin
 
TDC2017 | São Paulo - Trilha Programação Funcional How we figured out we had ...
TDC2017 | São Paulo - Trilha Programação Funcional How we figured out we had ...TDC2017 | São Paulo - Trilha Programação Funcional How we figured out we had ...
TDC2017 | São Paulo - Trilha Programação Funcional How we figured out we had ...
 
Python tutorial
Python tutorialPython tutorial
Python tutorial
 
Py Die R E A D M E
Py Die  R E A D M EPy Die  R E A D M E
Py Die R E A D M E
 
Into Clojure
Into ClojureInto Clojure
Into Clojure
 
From Java to Kotlin beyond alt+shift+cmd+k - Kotlin Community Conf Milan
From Java to Kotlin beyond alt+shift+cmd+k - Kotlin Community Conf MilanFrom Java to Kotlin beyond alt+shift+cmd+k - Kotlin Community Conf Milan
From Java to Kotlin beyond alt+shift+cmd+k - Kotlin Community Conf Milan
 
Kotlin Basics - Apalon Kotlin Sprint Part 2
Kotlin Basics - Apalon Kotlin Sprint Part 2Kotlin Basics - Apalon Kotlin Sprint Part 2
Kotlin Basics - Apalon Kotlin Sprint Part 2
 
Python programming : Abstract classes interfaces
Python programming : Abstract classes interfacesPython programming : Abstract classes interfaces
Python programming : Abstract classes interfaces
 
From java to kotlin beyond alt+shift+cmd+k - Droidcon italy
From java to kotlin beyond alt+shift+cmd+k - Droidcon italyFrom java to kotlin beyond alt+shift+cmd+k - Droidcon italy
From java to kotlin beyond alt+shift+cmd+k - Droidcon italy
 
Scala best practices
Scala best practicesScala best practices
Scala best practices
 

Similar to Beautiful python - PyLadies

An overview of Python 2.7
An overview of Python 2.7An overview of Python 2.7
An overview of Python 2.7decoupled
 
Learn 90% of Python in 90 Minutes
Learn 90% of Python in 90 MinutesLearn 90% of Python in 90 Minutes
Learn 90% of Python in 90 MinutesMatt Harrison
 
Python data structures
Python data structuresPython data structures
Python data structuresTony Nguyen
 
Python data structures
Python data structuresPython data structures
Python data structuresLuis Goldster
 
Python data structures
Python data structuresPython data structures
Python data structuresYoung Alista
 
Python data structures
Python data structuresPython data structures
Python data structuresFraboni Ec
 
Python data structures
Python data structuresPython data structures
Python data structuresHarry Potter
 
Python data structures
Python data structuresPython data structures
Python data structuresJames Wong
 
Stupid Awesome Python Tricks
Stupid Awesome Python TricksStupid Awesome Python Tricks
Stupid Awesome Python TricksBryan Helmig
 
Python 내장 함수
Python 내장 함수Python 내장 함수
Python 내장 함수용 최
 
Python_Cheat_Sheet_Keywords_1664634397.pdf
Python_Cheat_Sheet_Keywords_1664634397.pdfPython_Cheat_Sheet_Keywords_1664634397.pdf
Python_Cheat_Sheet_Keywords_1664634397.pdfsagar414433
 
Python_Cheat_Sheet_Keywords_1664634397.pdf
Python_Cheat_Sheet_Keywords_1664634397.pdfPython_Cheat_Sheet_Keywords_1664634397.pdf
Python_Cheat_Sheet_Keywords_1664634397.pdfsagar414433
 
Ruby Language - A quick tour
Ruby Language - A quick tourRuby Language - A quick tour
Ruby Language - A quick touraztack
 
The Vanishing Pattern: from iterators to generators in Python
The Vanishing Pattern: from iterators to generators in PythonThe Vanishing Pattern: from iterators to generators in Python
The Vanishing Pattern: from iterators to generators in PythonOSCON Byrum
 

Similar to Beautiful python - PyLadies (20)

An overview of Python 2.7
An overview of Python 2.7An overview of Python 2.7
An overview of Python 2.7
 
A tour of Python
A tour of PythonA tour of Python
A tour of Python
 
Python Workshop
Python  Workshop Python  Workshop
Python Workshop
 
Learn 90% of Python in 90 Minutes
Learn 90% of Python in 90 MinutesLearn 90% of Python in 90 Minutes
Learn 90% of Python in 90 Minutes
 
Python data structures
Python data structuresPython data structures
Python data structures
 
Python data structures
Python data structuresPython data structures
Python data structures
 
Python data structures
Python data structuresPython data structures
Python data structures
 
Python data structures
Python data structuresPython data structures
Python data structures
 
Python data structures
Python data structuresPython data structures
Python data structures
 
Python data structures
Python data structuresPython data structures
Python data structures
 
Stupid Awesome Python Tricks
Stupid Awesome Python TricksStupid Awesome Python Tricks
Stupid Awesome Python Tricks
 
Slides
SlidesSlides
Slides
 
Python 1
Python 1Python 1
Python 1
 
Python 내장 함수
Python 내장 함수Python 내장 함수
Python 내장 함수
 
Python_Cheat_Sheet_Keywords_1664634397.pdf
Python_Cheat_Sheet_Keywords_1664634397.pdfPython_Cheat_Sheet_Keywords_1664634397.pdf
Python_Cheat_Sheet_Keywords_1664634397.pdf
 
Python_Cheat_Sheet_Keywords_1664634397.pdf
Python_Cheat_Sheet_Keywords_1664634397.pdfPython_Cheat_Sheet_Keywords_1664634397.pdf
Python_Cheat_Sheet_Keywords_1664634397.pdf
 
Python Lecture 11
Python Lecture 11Python Lecture 11
Python Lecture 11
 
Ruby Language - A quick tour
Ruby Language - A quick tourRuby Language - A quick tour
Ruby Language - A quick tour
 
The Vanishing Pattern: from iterators to generators in Python
The Vanishing Pattern: from iterators to generators in PythonThe Vanishing Pattern: from iterators to generators in Python
The Vanishing Pattern: from iterators to generators in Python
 
Python lecture 05
Python lecture 05Python lecture 05
Python lecture 05
 

Recently uploaded

08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 

Recently uploaded (20)

08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 

Beautiful python - PyLadies

  • 1. Beautiful Python @alipeji | alicia@stylesage.co
  • 3. El outfit perfecto para un código pythonico
  • 4. La ropa interior tipos básicos @stylishcurves
  • 6. # Cadenas muy largas my_very_big_string = 'For a long time I used to go to bed early. ' + 'Sometimes, when I had put out my candle, my eyes would close ' + 'so quickly that I had not even time to say Im going to sleep.' my_very_big_string = '''For a long time I used to go to bed early. Sometimes, when I had put out my candle, my eyes would close so quickly that I had not even time to say Im going to sleep.''' my_very_big_string = ('For a long time I used to go to bed early. ' 'Sometimes, when I had put out my candle, my eyes would close ' 'so quickly that I had not even time to say Im going to sleep.')
  • 7. if stylesage.find('Fashion') != -1: pass # Comprobar si una cadena contiene otra stylesage = 'Fashion meets Big Data' if 'Fashion' in stylesage: pass
  • 8. >>> name = 'Alicia' >>> cats = 2 >>> print('My name is ' + name + ' and I have ' + str(cats) + ' cats') # Usa String Formatting!!
  • 9. #1 – “Old Style” >>> name = 'Bob' >>> 'Hello, %s' % name 'Hello, Bob' # String Formatting #2 – “New Style” String Formatting >>> name = 'Bob' >>> 'Hello, {}'.format(name) 'Hello, Bob' #3 – Literal String Interpolation # (Python 3.6+) >>> name = 'Bob' >>> f'Hello, {name}' 'Hello, Bob' #4 – Template Strings >>> from string import Template >>> t = Template('Hello, $name!') >>> t.substitute(name='Bob') 'Hello, Bob!'
  • 11. >>> if x >= start and x <= end: >>> pass >>> if len(items) != 0: >>> pass >>> if lang == 'Spanish': ... welcome = 'Bienvenido' ... else: ... welcome = 'Welcome' >>> if start <= x <= end: >>> pass >>> if items: >>> pass >>> welcome = 'Bienvenido' ... if lang == 'Spanish' else 'Welcome'
  • 12. Truth Value Testing Los siguientes valores serán evaluados como False en una comparación: ● None ● False ● Cero en cualquier tipo numérico, por ejemplo: 0, 0L, 0.0, 0j ● Cualquier secuencia vacía, por ejemplo: '', (), [] ● Los diccionarios vacíos: {} ● Las instancias de cualquier clase, si esta define los métodos __nonzero__() o __len__(), cuando estos métodos devuelven cero o False En cualquier otro caso, serán evaluados como True
  • 13. >>> values = [True, True, False, False] >>> i = 0 >>> flag = False >>> while not flag and i < len(values): ... flag = values[i] ... i += 1 >>> flag False >>> any(values) True # ¿algún True en la lista? >>> all(values) False
  • 14. >>> values = range(10) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> i = 0 >>> flag = False >>> while not flag and i < len(values): ... flag = (values[i] == 0) ... i += 1 >>> flag True >>> any(values) True # ¿algún 0 en la lista? >>> all(values) False
  • 16. >>> b, a = a, b>>> temp = a >>> a = b >>> b = temp >>> l = ['David', 'Pythonista', '555-55-55'] >>> name = l[0] >>> title = l[1] >>> phone = l[2] >>> name, title, phone = l >>> name, _, phone = l
  • 19. # Crear una tupla >>> arr = 'one', 'two', 'three' >>> arr[0] 'One' # Son immutables: >>> arr[1] = 'hello' TypeError: "'tuple' object does not support item assignment" >>> del arr[1] TypeError: "'tuple' object doesn't support item deletion" # Soportan múltiples # tipos de datos: >>> arr + (23,) ('one', 'two', 'three', 23)
  • 20. # namedtuples >>> from collections ... import namedtuple >>> Car = namedtuple('Car', ... 'color mileage automatic') >>> car1 = Car('red', 3812.4, True) # Acceder a los campos: >>> car1.color 'red' >>> car1.mileage 3812.4 >>> car1.automatic True # Los campos son inmutables: >>> car1.mileage = 12 AttributeError: "can't set attribute"
  • 22. # Crear una lista >>> arr = ['one', 'two', 'three'] >>> arr[0] 'One' # Son mutables: >>> arr[1] = 'hello' >>> arr ['one', 'hello', 'three'] >>> del arr[1] >>> arr ['one', 'three'] # Soportan múltiples tipos: >>> arr.append(23) >>> arr ['one', 'three', 23]
  • 23. # array slicing a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] >>> a[-1] 10 >>> a[2:8] [2, 3, 4, 5, 6, 7] >>> a[:5] [0, 1, 2, 3, 4] >>> a[5:] [5, 6, 7, 8, 9, 10] >>> a[2:8:2] [2, 4, 6] >>> a[::2] [0, 2, 4, 6, 8, 10] >>> a = [1, 2, 3, 4, 5] >>> a[2:4] = [0, 0, 0] >>> a [1, 2, 0, 0, 0, 5]
  • 24. Sets
  • 25. >>> A = {1, 2, 3, 3} >>> B = {3, 4, 5, 6, 7} >>> A set([1, 2, 3]) >>> B set([3, 4, 5, 6, 7]) >>> A | B set([1, 2, 3, 4, 5, 6, 7]) >>> A & B set([3]) >>> A - B set([1, 2]) >>> A ^ B set([1, 2, 4, 5, 6, 7])
  • 26. >>> A Counter({2: 2, 1: 1}) >>> B Counter({2: 2, 3: 1}) >>> C.most_common() [(3, 4), (1, 2), (2, 2), (4, 1), (5, 1), (6, 1), (7, 1)] >>> C.most_common(1) [(3, 4)] >>> C.most_common(3) [(3, 4), (1, 2), (2, 2)] >>> A = collections.Counter([1, 2, 2]) >>> B = collections.Counter([2, 2, 3]) >>> C = collections.Counter([1, 1, 2, 2, 3, 3, 3, 3, 4, 5, 6, 7]) >>> A | B Counter({2: 2, 1: 1, 3: 1}) >>> A & B Counter({2: 2}) >>> A + B Counter({2: 4, 1: 1, 3: 1})
  • 28. >>> a = ['Hello', 'world', '!'] >>> for i, x in enumerate(a): ... print '{}: {}'.format(i, x) >>> a = ['Hello', 'world', '!'] >>> i = 0 >>> for x in a: ... print '{}: {}'.format(i, x) ... i += 1 # Imprimir los elementos de una lista y su índice
  • 29. >>> squares = [x * x for x in range(10)]>>> even_squares = [] >>> for x in range(10): ... even_squares.append(x * x) >>> even_squares = [] >>> for x in range(10): ... if x % 2 == 0: ... even_squares.append(x * x) >>> even_squares = [x * x for x in range(10) ... if x % 2 == 0] # Obtener todos los cuadrados de los números del 0 al 9 # Obtener todos los cuadrados de los números pares del 0 al 9
  • 30. >>> zip(names, surnames) [('John', 'Cleese'), ('Eric', 'Idle'), ('Terry', 'Gilliam')] >>> names = ['John', 'Eric', 'Terry'] >>> surnames = ['Cleese', 'Idle', 'Gilliam'] >>> people = [] >>> for i in range(len(names)): ... people.append((names[i], surnames[i])) >>> print(people) [('John', 'Cleese'), ('Eric', 'Idle'), ('Terry', 'Gilliam')] # Obtener en una sola lista los pares nombre-apellido
  • 32. >>> squares = (i*i for i in xrange(1000000)) >>> next(squares) 0 >>> next(squares) 1 >>> next(squares) 4 >>> next(squares) 9 >>> next(squares) 16 >>> from collections import deque >>> q = deque(squares) >>> q.pop() 999998000001 >>> q.pop() 999996000004 >>> q.popleft() 0 >>> q.popleft() 1 >>> squares = [i*i for i in range(1000000)]
  • 33. # Add to the right >>> d = collections.deque() >>> d.extend([0, 1, 2, 3, 4]) deque([0, 1, 2, 3, 4]) >>> d.append(5) deque([0, 1, 2, 3, 4, 5]) # Add to the left >>> d = collections.deque() >>> d.extendleft([0, 1, 2, 3, 4]) deque([4, 3, 2, 1, 0]) >>> d.appendleft(5) deque([5, 4, 3, 2, 1, 0])
  • 34. >>> last_three = collections.deque(maxlen=3) >>> for i in xrange(5): ... last_three.append(i) ... print ', '.join( ... str(x) for x in last_three) 0 0, 1 0, 1, 2 1, 2, 3 2, 3, 4
  • 37. >>> name_for_userid = { ... 382: 'Alice', ... 950: 'Bob', ... 590: 'Dilbert', ... } >>> def greeting(userid): ... if userid in name_for_userid: ... return 'Hi %s!' % name_for_userid[userid] ... else: ... return 'Hi there!'
  • 38. >>> def greeting(userid): ... try: ... return 'Hi %s!' % name_for_userid[userid] ... except KeyError: ... return 'Hi there' >>> def greeting(userid): ... return 'Hi %s!' % user_dict.get(userid, 'there')
  • 39. >>> visits = { ... 'Alice': 0, ... 'Bob': 0, ... 'Dilbert': 0, ... } >>> def add_visit(user): ... if user not in visits: ... visits[user] = 0 ... visits[user] += 1 >>> def add_visit(user): ... visits.setdefault(user, 0) ... visits[user] += 1 >>> def add_visit(user): ... visits[user] = visits.get(user, 0) + 1 >>> visits = defaultdict(int) >>> def add_visit(user): ... visits[user] += 1
  • 41. >>> m = {x: x ** 2 for x in range(5)} >>> m {0: 0, 1: 1, 2: 4, 3: 9, 4: 16} >>> m = {x: 'A' + str(x) for x in range(5)} >>> m {0: 'A0', 1: 'A1', 2: 'A2', 3: 'A3', 4: 'A4', 5} >>> # Invertir las clave-valor >>> m = {'a': 1, 'b': 2, 'c': 3, 'd': 4} >>> {v: k for k, v in m.items()} {1: 'a', 2: 'b', 3: 'c', 4: 'd'}
  • 44. # * args >>> def test_var_args(f_arg, *argv): ... print "first normal arg:", f_arg ... for arg in argv: ... print "another arg through *argv :", arg >>> test_var_args() Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: test_var_args() takes at least 1 argument (0 given) >>> test_var_args('yasoob', 'python', 'eggs', 'test') 'first normal arg: yasoob' 'another arg through *argv : python' 'another arg through *argv : eggs' 'another arg through *argv : test'
  • 45. # ** kargs >>> def greet_me(**kwargs): ... for key, value in kwargs.iteritems(): ... print "%s == %s" %(key,value) >>> greet_me(name="yasoob") 'name == yasoob' >>> kwargs = {"arg3": 3, "arg2": "two", "arg1":5} >>> greet_me(**kwargs) 'arg1 == 5' 'arg2 == two' 'arg3 == 3'
  • 47. >>> def apply_discount(product, discount): ... price = int(product['price'] * (1.0 - discount)) ... assert 0 <= price <= product['price'] ... return price >>> shoes = {'name': 'Fancy Shoes', 'price': 14900} >>> apply_discount(shoes, 0.25) 11175 >>> apply_discount(shoes, 2.0) Traceback (most recent call last): File "<input>", line 1, in <module> apply_discount(prod, 2.0) File "<input>", line 4, in apply_discount assert 0 <= price <= product['price'] AssertionError
  • 48. # internamente un assert es... >>> if __debug__: ... if not expression1: ... raise AssertionError(expression2) # por eso nunca hay que hacer... >>> def delete_product(prod_id, user): >>> assert user.is_admin(), 'Comprueba si es administrador' >>> assert store.has_product(prod_id), 'Comprueba si existe' >>> store.get_product(prod_id).delete()
  • 50. // WARNING!! Código Java en una charla Python!! void muestraContenido(String archivo) throws FileNotFoundException, IOException { String cadena; FileReader f = new FileReader(archivo); BufferedReader b = new BufferedReader(f); while((cadena = b.readLine())!=null) { System.out.println(cadena); } b.close(); }
  • 51. with open(fname, 'r') as file_in: print file_in.read()
  • 52. class File(): def __init__(self, filename, mode): self.filename = filename self.mode = mode def __enter__(self): self.open_file = open(self.filename, self.mode) return self.open_file def __exit__(self, *args): self.open_file.close()
  • 53. Referencias Python Tricks: The Book A Buffet of Awesome Python Features 30 Python Language Features and Tricks You May Not Know About PYTHON TIPS web