Python

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

str(77)

Convert to integer

int('77')

Convert to float

float('7.7')

Check types

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

Logging

import logging
logging.warn('warning')

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:

while True:
    print('Username:')
    username = raw_input()
    if username != 'jack':
        continue
    print('Hello, Jack. What is the password?')
    password = raw_input()
    if password == 'aloha':
        break
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)
try:
	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'):
        os.unlink(filename)

Leave a Reply

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