Skip to content

Instantly share code, notes, and snippets.

@tuannvm
Last active September 11, 2022 00:05
Show Gist options
  • Save tuannvm/7d8f335a6337f9e58f974a0f4f170e8e to your computer and use it in GitHub Desktop.
Save tuannvm/7d8f335a6337f9e58f974a0f4f170e8e to your computer and use it in GitHub Desktop.
python cheatsheet! #cheatsheet

Introduction

Set

a = {1, 2, 3}

a.add(1)

{1,2,3}

Loop

  • For

Full form

dataList = []
tempList = []
for elem in dataList:
    tempList.append(func(elem))

print dataList

Short form

tempList = [func(elem) for elem in dataList]

File I/O

  • Open()

open (<filename>, <access mode>)

w a w+

# open file data.out in write mode
out = open("data.out", "w") 

# write "content" to out
print >>out, "content"

# close the file when done
out.close()
  • finally

when you have a situation when code must always run no matter what erros occur.

if you try to change an immutable value, Python raises a TypeError exception

data = open('file.txt')

# using locals() to check whether data object (file.txt represent) exists or not
if 'data' in locals():
        data.close()
  • with

with open('file.txt', 'w') as data:
    print >>data, "content here"

is equivalent to

data = open('file.txt', 'w')
print >>data, "content here"
data.close()

without additional close()

And also, two with statements````` can be combined with comma ","

OOP


Inheritance

class Decimal(object):
    """ define base class """
    def __init__(self, number, place):
        self.number = number
        self.place = place

    def __repr__(self):
        """ method to automatically return the value when call class itself"""
        return "%.{}f".format(self.place) % self.number

class Currency(Decimal):
    def __init__(self, number, place, symbol):
        """ inherit from Decimal class, initilize the attribute which base class support """
        super(Currency, self).__init__(number, place)
        self.symbol = symbol

    def __repr__(self):
        """ use the __repr__ method from base class to get the value """
        return "{}{}".format(self.symbol, super(Currency, self).__repr__())

print Decimal(2,5)
print Currency(3,5,'$')     
@tuannvm
Copy link
Author

tuannvm commented May 11, 2019

Install python with sqlite3 support on mac os

CFLAGS="-I$(xcrun --show-sdk-path)/usr/include" pyenv install <version>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment