Popularity of Python:

Python is general purpose programming language.
Python is adopted in scientific computing and machine learning areas.

The Zen of Python

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!
 ~ Tim Peters

Python Standard Types

  • Numeric type: int - no decimal points; int_var = 5
  • Numeric type: float - real numbers with decimal points; flt_var = 7.4
  • String - sequence of characters; str_var = 'str'
  • List - mutable, stores multiple members; list_vaar = [1, 2.5, 'str']
  • Tuple - immutable, stores multiple members; tpl_var = (2, 4.7, 'abc')
  • Dictionary - key-value pairs; dict_var = {'planet': 'Mars', 'population': 0}
SUFFIXES = {1000: ['KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'],
	1024: ['KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB']}
def approximate_size(size, kilobyte_is_1024_bytes=True):
	'''Convert a file size to human-readable form.
	Keyword arguments:
	size -- file size in bytes
	kilobyte_is_1024_bytes -- if True (default), use multiples of 1024
	if False, use multiples of 1000
	Returns: string
	if size < 0:
		raise ValueError('number must be non-negative')
	multiple = 1024 if kilobyte_is_1024_bytes else 1000
	for suffix in SUFFIXES[multiple]:
		size /= multiple
		if size < multiple:
			return '{0:.1f} {1}'.format(size, suffix)
	raise ValueError('number too large')
approximate_size(1000000000000, False) # 1.0 TB
approximate_size(1000000000000) # 931.3 GiB
approximate_size(size=4000, kilobyte_is_1024_bytes=False) # 4.0 KB
approximate_size(kilobyte_is_1024_bytes=False, size=4000) # 4.0 KB

Working with string

Convert to string (Casting to string)


Convert to integer


Convert to float


Check types

isinstance([], list) # True
isinstance({}, dict) # True
isinstance('', str) # True
type([]) is list # True
type({}) is dict # True
type('') is str # True
type(0) is int # True
type({}) # <type 'dict'>
type([]) # <type 'list'>


import logging

if-elif-else-endif in Jinja templates

{% if kenny.sick %}
    Kenny is sick.
{% elif kenny.dead %}
    You killed Kenny! You bastard!!!
{% else %}
    Kenny looks okay. So far.
{% endif %}


while True:
    username = raw_input()
    if username != 'jack':
    print('Hello, Jack. What is the password?')
    password = raw_input()
    if password == 'aloha':
print('Access granted.')

Clear session:

self.session.pop('session_data', None)

Safe conversion to int (safe int casting):

card_amount = self.request.POST.get('card_amount', 0)
	card_amount = int(card_amount)
except(ValueError, TypeError):
	card_amount = 0

Delete all text files

import os
for filename in os.listdir():
    if filename.endswith('.txt'):

Pythonic way

# Looping over a range of numbers
for i in [0, 1, 2, 3, 4, 5]:
    print i**2
# Looping over a range of numbers in a pythonic way
for i in range(6):
    print i**2
# Looping over a collection
colors = ['red', 'green', 'blue']
for i in range(len(colors)):
    print colors[i]
# Looping over a collection in a pythonic way
colors = ['red', 'green', 'blue']
for color in colors:
    print color
# Looping backwards
colors = ['red', 'green', 'blue']
for i in range(len(colors)-1, -1, -1):
    print colors[i]
# Looping backwards in a pythonic way
colors = ['red', 'green', 'blue']
for color in reversed(colors):
    print color
# Looping over a collection and indicies
colors = ['red', 'green', 'blue']
for i in range(len(colors)):
    print i, '-->', colors[i]
# Looping over a collection and indicies in a pythonic way
colors = ['red', 'green', 'blue']
for i, color in enumerate(colors):
    print i, '-->', color
# Looping in sorted order in a pythonic way
colors = ['red', 'green', 'blue']
for color in sorted(colors):
    print color
# Looping in sorted reversed order in a pythonic way
colors = ['red', 'green', 'blue']
for color in sorted(colors, reverse=True):
    print color
# Function calls with keyword arguments
twitter_search('@tesla', False, 20, True)
# Function calls with keyword arguments in a pythonic way
twitter_search('@tesla', retweets=False, numtweets=20, popular=True)
# Concatenating strings
colors = ['red', 'green', 'blue']
s = colors[0]
for color in colors[1:]:
    s += ', ' + color
print s
# Concatenating strings in a pythonic way
colors = ['red', 'green', 'blue']
print ', '.join(colors)

Leave a Reply

Your email address will not be published. Required fields are marked *