Skip to content

Instantly share code, notes, and snippets.

@juanmaguitar
Last active March 24, 2018 21:07
Show Gist options
  • Select an option

  • Save juanmaguitar/31c1459a8d8b083210300dffb19121f2 to your computer and use it in GitHub Desktop.

Select an option

Save juanmaguitar/31c1459a8d8b083210300dffb19121f2 to your computer and use it in GitHub Desktop.
NOTES PYTHON

Python Notes

Resources

First Steps

Run programs

  • python hello.py → executes hello.py using python interpreter 2.x
  • python3 hello.py → executes hello.py using python interpreter 3.x

Display Version

  • python --version → displays python version

Updating Python Version

Install python

  • sudo apt-get install python3.6 → Install specific version of python

To link python with latest version of python

cd /usr/bin
sudo rm python
sudo ln -s python3.4 python

Dependencies

Show and save dependencies

  • pip3 freeze --local → shows modules installed for this project
  • pip3 freeze --local > requirements.txt → persist modules installed for this project in a file

Install/Uninstall dependencies

  • pip3 install flask → install module
  • pip3 uninstall flask → uninstall module

Tip

  • sudo !! → run previous command as admin

Install dependencies from file

  • sudo pip3 install -r requirements → install modules from file dependencies

Packages

The init.py files are required to make Python treat the directories as containing packages; this is done to prevent directories with a common name, such as string, from unintentionally hiding valid modules that occur later on the module search path. In the simplest case, init.py can just be an empty file, but it can also execute initialization code for the package or set the all variable, described later.

.
├── libs
│   ├── __init__.py
│   └── byotest.py
├── src
│   ├── __init__.py
│   └── sum.py
└── test
    ├── __init__.py
    └── sum_test.py

Being...

test/sum_test.py

from libs.byotest import test_are_equal, test_not_equal, test_is_in, test_not_in, test_between
from src.sum import sum

test_are_equal(sum(2,3), 5)
test_are_equal(sum(2,"3"), 5)
test_not_equal(sum(2,"3"), 0)
test_is_in([4,5,6], sum(2,"3"))
test_not_in([0,1,2,3,4], sum(2,"3"))
test_between([2,8], sum(2,"3"))

print("All tests pass!!")

libs/byotest.py

def test_are_equal(actual, expected):
    assert expected == actual, "Expected {0}, got {1}".format(expected, actual)


def test_not_equal(a, b):
    assert a != b, "Did not expect {0}, but got {1}".format(a, b)


def test_is_in(collection, item):
    assert item in collection, "{0} does not contain {1}".format(collection, item)

def test_not_in(collection, item):
    assert item not in collection, "{0} does contain {1}".format(collection, item)

def test_between(minMaxRange, item):
    min = minMaxRange[0]
    max = minMaxRange[1]
    rangeList = list(range(min,max))
    assert item in rangeList, "{0} does not contain {1}".format(rangeList, item)

src/sum.py

def sum(a,b):
    return int(a)+int(b)

With this structure we can do..

python -m test.sum_test

To remove all *.pyc files and pycache directories recursively in the current directory.

find . | grep -E "(__pycache__|\.pyc|\.pyo$)" | xargs rm -rf

Ternary Operator

http://book.pythontips.com/en/latest/ternary_operators.html

  • condition_is_true if condition else condition_is_false
is_fat = True
state = "fat" if is_fat else "not fat"
>>> [1 for c in "hola soy JuanMa" if c.isupper()]
[1, 1]
>>> [c.isupper() for c in "hola soy JuanMa"]
[False, False, False, False, False, False, False, False, False, True, False, False, False, True, False]
>>> [1 if c == 'o' else 0 for c in "hola soy JuanMa"]
[0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0]

List comprehension (like js filter)

>>> [element for element in range(10) if not(element % 2)]
[0, 2, 4, 6, 8]

Enumerate list

>>> ls = list(range(10))
>>> for index, value in enumerate(ls):
...   print(value, index)
0 0
1 1
2 2
3 3
4 4
5 5
6 6
7 7
8 8
9 9
>>>

Files I/O

File Modes

Basic

  • r → (default) Open a file for reading. (default)
  • w → Open a file for writing. Creates a new file if it does not exist or truncates the file if it exists.
  • a → Open for appending at the end of the file without truncating it. Creates a new file if it does not exist.

Extra

  • x → Open a file for exclusive creation. If the file already exists, the operation fails.
  • t → Open in text mode. (default)

Added

  • b (rb, wb, ab) → Open in binary mode.
  • + → Open a file for updating (reading and writing)
    • r+ → read/write (if file doesn't exist it will throw an error. If it does → content overwritten )
    • w+ → read/write (file will be created if it doesn't exist. Anycase → content overwritten)
    • a+ → read/append (file will be created if it doesn't exist. Anycase → content appended)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment