Python Flashcards
Companies which use Python at sacle
Youtube, Dropbox
Frameworks
Web applications and API Design
Django, Flask, Pyramid
Configuration
Ansible, Boto for AWS
Data Analysis
Pandas, MatplotLib, Bokeh, Tensoflow, SciKitLearn
Language Features
- strongly typed - every object has a definite type
- dynamically typed - no type checking of code prior to running it
- uses duck-typing - suitability of an object is decided at run time
(Java is statically typed - compiler does typechecking) - interpreted language
- syntax - clear readable and expressive
- used whitespace to distinguish code blocks so reduced all the parentheses used by other languages
There are multiple interpretations of Python
- CPython (written in C)
- Jython - targets JVM
- IronPython - .NET
- PyPy - R
Versions
2/3
Batteries Included
- large amount of libraries
Zen Of Python
> > > import this
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!
Python REPL
Read Eval Print Loop
4 spaces for indentation
all constructs end with colon :
PEP
Python Enhancement Proposal
PEP 8 - style guide for python
PEP 20 - Zen of Python
Get help for any module
> > > help(module_name)
help(math)
prints all functions and descriptions
> > > help(math.factorial)
Import Modules
this will import full library into the current namespace
»> import math
»> math.factorial(10)
this will import only one function into current namespace
»> from math import factorial
»> factorial(10)
> > > from math import factorial as f
Built In Data Types
Scalar types - int, float, None, bool
int
- has unlimited precision
- binary => 0b10 == 2
- hex => 0x10 == 16
- convert string to int => int(“300”) == 300
float
- 3e8 == 300000000
- convert integer to float => float(7) == 7.0, float(“1.23”) == 1.23
None
- no value
bool
- only 0 integer is false rest all are true
- only 0.0 float is false rest all are true
- only empty string i.e. “” is false
- only empty list i.e. [] is false
bool([]) - False
bool([1, 2, 3]) - True
bool(“”) - False
Control Flow Structures
Breaking a while loop
if expression:
print(“”)
else:
print(“”)
while exp:
print()
while expression:
if expressions:
break;
String Datatype (str)
- IMMUTABLE sequence of unicode chars
- string literals (not objects) can use single or double quotes
- multiline string use three quotes i.e. “”” fssfss “””
- create strings from other type use str() constructor i.e. str(10.7) => “10.7”
- help(str) -> gives all methods
- strings are sequence types i.e. they support certain interface operations i.e. indexing,
c = 'oslo' c1 = c.capitalize()
c was not modified but instead anew string was created. Because strings are immutable.
Bytes
- IMMUTABLE sequences of Bytes
- default encoding is UTF-8
- need to prefix them with lowercase b
i. e. b’hello’ or b”hello”
split returns a list of byte objects
»> split(b’hello world’)
»> [b’hello’, b’world’]
**** very important ***
encoding - converts strings to bytes
decoding - converts bytes to string
all http response, files etc are transmitted as bytes but we choose to work in string with UTF-8 encoding
nor = “some norwegian chars”
data = nor.encode(“UTF-8”)
»> data
»> b’norwegian chars’
Lists
- MUTABLE sequences of objects
- a = [1, 2, 3]
- append()
list constructor - used to create list from other objects
»> list(“hello”)
»> [‘h’, ‘e’, ‘l’, ‘l’, ‘o’]
Dictionary
- MUTABLE map of key to value
- d = {“alice”:”123”, “bob”: “456”}
- retrieve value using key i.e. d[“alice”]
- adding new value, d[‘jina’] = ‘487’
- can update values on the fly
- d[“alice”] = “000”
For Loop
cities = [“London”, “Paris”, “Berlin”]
for city in cities:
print(city)
countries = {“usa”: “washington”, “england”: “london”}
for country in countries:
print(capitals[country])
for country, capital in countries:
print(country, capital)
Decoding and Encoding
names = [b”alice”, b”bob”, b”cindy”]
for name in names:
print(name.decode(“UTF-8”))
Functions
- special attributes are delimited by double underscores
- functions args are pass by object reference not pass by value of the object
__name__
- evals to __main__ if we execute python3 filename.py
- evals to actual module name if imported
from hello import (foo, bar) => import only certain funcs
from hello import * => import everything
- Doc String
def foo(arg):
“”” This is a function
Args:
bar: this is bar
Returns:
A message
“””
return “foo”
Command Line args
## hello.py import sys
if __name__ == “__main__”:
print(sys.argv[0], sys.argv[1])
python3 hello.py “foo”
> > > hello, foo
argv[0] - filename
id() function
gives back id of an object i.e. 10 in this case and not the id of reference i.e. i
there is object and . object reference
i.e. i = 10
i is object reference and 10 is the integer object
====> named references to objects
i = 10
id(i) => 244224355343
i += 10
id(i) => 5345452345342
Python does not have variables per se. It only has named references to object - which allows us to retrieve objects
value equality and identity are different
- a variable can have the same value as another variable but is not necessarily the same object
Python objects
p = [1, 2, 3] q = [1, 2, 3]
p == q => T
p is q => F