Skip to content

Instantly share code, notes, and snippets.

@firhatsungkar
Created April 29, 2019 09:03
Show Gist options
  • Save firhatsungkar/7e80bd4e7b1fc69927eeee852f14f8b8 to your computer and use it in GitHub Desktop.
Save firhatsungkar/7e80bd4e7b1fc69927eeee852f14f8b8 to your computer and use it in GitHub Desktop.

Python Cheat Sheet

Dependency in Python

  • virtualenv venv -p /usr/local/bin/python3
  • source ./venv/bin/activate
  • pip freeze > requirements.txt
  • pip install -r requirements.txt

Check for None (Null)

Use foo is None instead foo == None

Mutable

  • check memory ```id(foo)``
  • foo.append(1) —> mutable (id same)
  • foo = 1 —> immutable (id changed)

Execute a Python Script

add on first line: #! /usr/bin/env python

Format String

  • Multiline
multiline= """Will's ball
... is red
... and bouncy!"""
  • Format string:
print("Will's %s is %s." % (item, color))
  • Format with .format
print("Will's {0} is {1}".format(item, color))

Python Method

  • See available method with dir()
  • method help with help("will".rstrip)

Flow Control

  • if (condition):
    • elif (condition):
    • else:
  • for i in range(5):
  • range(min, max, increase/decrese)
    • range(10, 0, -1)

Comparison Operators

  • ==, !=, >, <. <=, >=
  • and, or, is, in

Lists

  • [] ex: [1, 'cat', 7, {'car': 'chevy'}]
  • [].append(element)
  • [].remove(element)
  • [].pop(index = element.count() -1)
  • [].sort()
  • [].reverse()
  • [].count()
  • slice with [][fromIndex:position]
a = [1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> a[2:5]
[3, 4, 5]

>>> a[2:]
[3, 4, 5, 6, 7, 8, 9]
>>> a[:5]
[1, 2, 3, 4, 5]
>>> a[-4:]
[6, 7, 8, 9]

>>> a[2:5] = ['foo', 'bar', 'baz']
>>> a
[1, 2, 'foo', 'bar', 'baz', 6, 7, 8, 9]

>>> zoo_animals = ['giraffe', 'monkey', 'elephant', 'lion', 'bear', 'pig', 'horse', 'aardvark']
>>> my_animals = ['monkey', 'bear', 'pig']

>>> not_my_animals = []
>>> for animal in zoo_animals:
...     if animal not in my_animals:
...             not_my_animals.append(animal)
... 
>>> not_my_animals
['giraffe', 'elephant', 'lion', 'horse', 'aardvark']

>>> other_animals = [animal for animal in zoo_animals if animal not in my_animals]
>>> other_animals
['giraffe', 'elephant', 'lion', 'horse', 'aardvark']

Manipulate Data with Dictionaries

  • key in {}
  • del dict[‘key’]
  • get value: dict.get(‘key1’, ‘default value’)

Immutable Data with Tupple

  • t = 'dog', 'cat', 12345

Unique Unordered Collections with Set

  • animals = {'monkey', 'bear', 'dog', 'monkey', 'cat', 'bear', 'gorilla'}
  • fish = set()
  • add, remove, pop, in, union

Logging in Python

  • import logging
  • logging.warning
  • critical, error, warning, info, debug
  • logging.basicConfig(filename='./demo.log', level=logging.INFO
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment