[20]:
import this
The Zen of Python, by Tim Peters
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!
1. I. Native DataTypes¶
1.1. Number¶
[2]:
## integer
a = 1
b = 0x10 # 16
print(type(a)) # <class 'int'>
<class 'int'>
[3]:
## float
c = 1.2
d = .5 # 0.5
g = .314e1 # 3.14
print(type(g)) # <class 'float'>
<class 'float'>
[4]:
## complex
e = 1+2j
f = complex(1, 2)
print(type(e)) # <class 'complex'>
print(f == e) # True
<class 'complex'>
True
[21]:
## Operators: + - * / ** // %
print(1 + 1)
print(2 - 2)
print(3 * 3)
print(5 / 4)
print(2 ** 10)
print(5 // 4)
print(5 % 4)
2
0
9
1.25
1024
1
1
[27]:
## Casting
### Integer -> Float
print(float.__doc__)
print(float(3))
print(3 / 1)
print(float("3.14"))
float(x) -> floating point number
Convert a string or number to a floating point number, if possible.
3.0
3.0
3.14
[28]:
### Float -> Integer
print(int.__doc__)
int(x=0) -> integer
int(x, base=10) -> integer
Convert a number or string to an integer, or return 0 if no arguments
are given. If x is a number, return x.__int__(). For floating point
numbers, this truncates towards zero.
If x is not a number or if base is given, then x must be a string,
bytes, or bytearray instance representing an integer literal in the
given base. The literal can be preceded by '+' or '-' and be surrounded
by whitespace. The base defaults to 10. Valid bases are 0 and 2-36.
Base 0 means to interpret the base from the string as an integer literal.
>>> int('0b100', base=0)
4
[41]:
print(int(3.14)) # 3
print(int("3", base = 10)) # 3
print(int("1010", base = 2)) # 10
print(int("0b1010", base = 0)) # 10
3
3
10
10
1.2. String¶
[1]:
s1 = ':dog:\n'
s2 = "Dogge's home"
s3 = """
Hello,
Dogge!
"""
print(type(s1)) # <class 'str'>
print("%s, %s, %s" % (s1, s2, s3))
<class 'str'>
:dog:
, Dogge's home,
Hello,
Dogge!
[6]:
## Length
print(len(s1)) # 2
2
[4]:
## Slicing
s = 'study and practice'
print('{0}:{1}'.format(s[:5], s[-8:])) # study:practice
study:practice
[48]:
## Operator: +
print("abc" + "." + "xyz")
abc.xyz
[47]:
## Casting
print(str.__doc__)
print(str(3.14))
print(str(3))
print(str([1,2,3]))
print(str((1,2,3)))
print(str({1,2,3}))
print(str({'python': '*.py', 'javascript': '*.js'}))
str(object='') -> str
str(bytes_or_buffer[, encoding[, errors]]) -> str
Create a new string object from the given object. If encoding or
errors is specified, then the object must expose a data buffer
that will be decoded using the given encoding and error handler.
Otherwise, returns the result of object.__str__() (if defined)
or repr(object).
encoding defaults to sys.getdefaultencoding().
errors defaults to 'strict'.
3.14
3
[1, 2, 3]
(1, 2, 3)
{1, 2, 3}
{'python': '*.py', 'javascript': '*.js'}
1.3. Byte¶
[8]:
# Byte
## 0-255/x00-xff
byt = b'abc'
print(type(byt)) # <class 'bytes'>
print(byt[0] == 'a')# False
print(byt[0] == 97) # True
<class 'bytes'>
False
True
[9]:
## Length
print(len(byt)) # 3
3
1.5. None¶
[11]:
print(None is None) # True
print(type(None)) # <class 'NoneType'>
True
<class 'NoneType'>
1.6. List¶
[12]:
l = ['python', 3, 'in', 'one']
print(type(l)) # <class 'list'>
<class 'list'>
[13]:
## Length
print(len(l)) # 4
4
[14]:
## Slicing
print(l[0]) # 'python'
print(l[-1]) # 'one'
print(l[1:-1]) # [3, 'in']
python
one
[3, 'in']
[15]:
## Alter
l.append('pic') # None
print(l)
# l == ['python', 3, 'in', 'one', 'pic']
l.insert(2, '.4.1') # None
print(l)
# l == ['python', 3, '.4.1', 'in', 'one', 'pic']
l.extend(['!', '!'])
print(l)
# l == ['python', 3, '.4.1', 'in', 'one', 'pic', '!', '!']
['python', 3, 'in', 'one', 'pic']
['python', 3, '.4.1', 'in', 'one', 'pic']
['python', 3, '.4.1', 'in', 'one', 'pic', '!', '!']
[16]:
print(l.pop()) # '!'
print(l)
# l == ['python', 3, '.4.1', 'in', 'one', 'pic', '!']
print(l.pop(2)) # '.4.1'
print(l)
# l == ['python', 3, 'in', 'one', 'pic', '!']
l.remove("in")
print(l)
# l == ['python', 3, 'one', 'pic', '!']
del l[2]
print(l)
# l == ['python', 3, 'pic', '!']
!
['python', 3, '.4.1', 'in', 'one', 'pic', '!']
.4.1
['python', 3, 'in', 'one', 'pic', '!']
['python', 3, 'one', 'pic', '!']
['python', 3, 'pic', '!']
[17]:
print(l.index('pic')) # 2
2
1.7. Tuple¶
[18]:
tp = (1, 2, 3, [4, 5])
print(type(tp)) # <class 'tuple'>
<class 'tuple'>
[19]:
## Length
print(len(tp)) # 4
print(tp[2]) # 3
tp[3][1] = 6
print(tp) # (1, 2, 3, [4, 6])
4
3
(1, 2, 3, [4, 6])
[20]:
## Single element
tp = (1, ) # Not tp = (1)
print(tp)
(1,)
[21]:
## Assign multiple values at once
v = (3, 2, 'a')
(c, b, a) = v
print(a, b, c) # a 2 3
a 2 3
1.8. Set¶
[22]:
st = {'s', 'e', 'T'}
print(type(st)) # <class 'set'>
<class 'set'>
[23]:
## Length
print(len(st)) # 3
3
[24]:
## Empty
st = set()
print(len(st)) # 0
0
[25]:
st = {}
print(type(st)) # <class 'dict'>
<class 'dict'>
[5]:
## Alter
st = set(['s', 'e', 'T'])
st.add('t') # st == {'s', 'e', 't', 'T'}
st.add('t') # st == {'s', 'e', 't', 'T'}
st.update(['!', '!'])
print(st)
# st == {'s', 'e', 't', 'T', '!'}
st.discard('t') # st == {'T', '!', 's', 'e'} # No Error
st.remove('T') # st == {'s', 'e', '!'} # KeyError
st.pop() # 's'
print(st)
# st == {'e'}
st.clear() # st == set()
print(st)
{'T', '!', 's', 't', 'e'}
{'s', 'e'}
set()
1.9. Dict¶
[2]:
dic = {}
print(type(dic)) # <class 'dict'>
dic = {'k1': 'v1', 'k2': 'v2'}
print(dic)
<class 'dict'>
{'k2': 'v2', 'k1': 'v1'}
[3]:
## Length
print(len(dic)) # 2
2
[4]:
print(dic['k2']) # 'v2'
print(dic.get('k1')) # 'v1'
print(dic.get('k3', 'v0')) # 'v0'
dic['k2'] = 'v3'
print(dic) # {'k1': 'v1', 'k2': 'v3'}
print('k2' in dic) # True
print('v1' in dic) # False
v2
v1
v0
{'k2': 'v3', 'k1': 'v1'}
True
False
2. III. Flow Control¶
2.1. If¶
[6]:
import sys
if sys.version_info.major < 3:
print("Version 2.X")
elif sys.version_info.major > 3:
print("Future")
else:
print("Version 3.X")
Version 3.X
2.2. Loop¶
for
[49]:
for i in "Hello":
print(i)
H
e
l
l
o
while
[8]:
prod = 1
i = 1
while i < 10:
prod = prod * i
i += 1
print(prod)
362880
[59]:
## break & continue
for n in range(2, 10):
if n % 2 == 0:
print("Found an even number ", n)
continue
if n > 5:
print("n > 5!")
break
Found an even number 2
Found an even number 4
Found an even number 6
n > 5!
[57]:
## continue
for num in range(2, 10):
if num % 2 == 0:
print("Found an even number", num)
continue
print("Found a number", num)
Found an even number 2
Found a number 3
Found an even number 4
Found a number 5
Found an even number 6
Found a number 7
Found an even number 8
Found a number 9
2.3. Comprehension¶
List
[18]:
s = [2 * x for x in range(10) if x ** 2 > 3]
print(s)
pairs = [(x, y) for x in range(2) for y in range(2)]
print(pairs)
[4, 6, 8, 10, 12, 14, 16, 18]
[(0, 0), (0, 1), (1, 0), (1, 1)]
Set
[17]:
s = {2 * x for x in range(10) if x ** 2 > 3}
print(s)
pairs = set([(x, y) for x in range(2) for y in range(2)])
print(pairs)
{4, 6, 8, 10, 12, 14, 16, 18}
{(0, 1), (1, 0), (0, 0), (1, 1)}
Dict
[15]:
ls = {s: len(s) for s in ["Python", "Javascript", "Golang"]}
print(ls)
sl = {v: k for k, v in ls.items()}
print(sl)
{'Python': 6, 'Javascript': 10, 'Golang': 6}
{10: 'Javascript', 6: 'Golang'}
2.4. Iterators & Generators¶
[30]:
python = iter("Python")
print(python)
for i in python:
print(i)
<str_iterator object at 0x10293f8d0>
P
y
t
h
o
n
[32]:
def reverse(data):
for index in range(len(data)-1, -1, -1):
yield data[index]
nohtyp = reverse("Python")
print(nohtyp)
for i in nohtyp:
print(i)
<generator object reverse at 0x1029539e8>
n
o
h
t
y
P
3. IV. Function¶
3.1. Definition¶
[64]:
def f():
"""return 'Hello, World!'"""
return "Hello, World!"
print(f())
print(f.__doc__)
Hello, World!
return 'Hello, World!'
3.2. Arguments¶
[69]:
## default arguments
def f(name = "World"):
"""return 'Hello, $name'"""
return "Hello, {}!".format(name)
print(f())
print(f("Python"))
Hello, World!
Hello, Python!
[74]:
## keyword arguments
def f(v, l = "Python"):
"""return '$v, $l'"""
return "{}, {}!".format(v, l)
print(f("Hello"))
print(f("Bye", "C/C++"))
Hello, Python!
Bye, C/C++!
[102]:
## arbitrary arguments
def f(*args, con = " & "):
print(isinstance(args, tuple))
print("Hello", con.join(args))
f("Python", "C", "C++", con = "/")
True
Hello Python/C/C++
[107]:
def f(*args, **kargs):
print("args ", args)
print("kargs ", kargs)
print("FP: {} & Scripts: {}".format(kargs.get("fp"), "/".join(args)))
f("Python", "Javascript", ms = "C++", fp = "Haskell")
args ('Python', 'Javascript')
kargs {'ms': 'C++', 'fp': 'Haskell'}
FP: Haskell & Scripts: Python/Javascript
3.3. Lambda¶
[112]:
pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]
pairs.sort(key=lambda pair: pair[1])
print(pairs)
pairs.sort(key=lambda pair: pair[0])
print(pairs)
[(4, 'four'), (1, 'one'), (3, 'three'), (2, 'two')]
[(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]
3.4. @decorator¶
[120]:
def log(f):
def wrapper():
print("Hey log~")
f()
print("Bye log~")
return wrapper
@log
def fa():
print("This is fa!")
# Equal to...
def fb():
print("This is fb!")
fb = log(fb)
fa()
print("*"*10)
fb()
Hey log~
This is fa!
Bye log~
**********
Hey log~
This is fb!
Bye log~
4. V. Class(OOP)¶
5. class¶
[10]:
class Animal:
"""This is an Animal"""
def fly(_):
print("I can fly!")
a = Animal()
a.fly() # I can fly!
print(a.__doc__) # This is an Animal
I can fly!
This is an Animal
6. __init__ & self¶
[15]:
class Animal:
"""This is an Animal"""
def __init__(self, can_fly = False):
print("Calling __init__() when instantiation!")
self.can_fly = can_fly
def fly(self):
if self.can_fly:
print("I CAN fly!")
else:
print("I can not fly!")
a = Animal() # Calling __init__() when instantiation!
a.fly() # I can not fly!
b = Animal(can_fly = True) # Calling __init__() when instantiation!
b.fly() # I CAN fly!
Calling __init__() when instantiation!
I can not fly!
Calling __init__() when instantiation!
I CAN fly!
7. Instance¶
[19]:
class Animal:
pass
class Human:
pass
a = Animal()
h = Human()
print(isinstance(a, Animal))
print(isinstance(h, Animal))
True
False
8. Inheritance¶
[5]:
class Animal:
"""This is an Animal"""
def __init__(self, can_fly = False):
self.can_fly = can_fly
def fly(self):
if self.can_fly:
print("I CAN fly!")
else:
print("I can not fly!")
class Dog(Animal):
"""This is a Dog"""
def bark(self):
print("Woof!")
d = Dog()
d.fly()
d.bark()
I can not fly!
Woof!
9. Override¶
[25]:
class Animal:
"""This is an Animal"""
def __init__(self, can_fly = False):
self.can_fly = can_fly
def fly(self):
if self.can_fly:
print("I CAN fly!")
else:
print("I can not fly!")
class Bird:
"""This is a Bird"""
def fly(self):
print("I'm flying high!")
bird = Bird()
bird.fly() # I'm flying high!
I'm flying high!
10. VI. Module¶
10.1. import¶
[37]:
import os
print(os.name)
from sys import version_info as PY_VERSION
print("VERSON: {}.{}".format(PY_VERSION.major, PY_VERSION.minor))
from math import *
print(pi)
posix
VERSON: 3.5
3.141592653589793
10.2. Search Path¶
- current directory
echo $PYTHONPATHsys.path
10.3. Package¶
[40]:
"""
MyModule/
|--SubModuleOne/
|--__init__.py
|--smo.py
# smo.py
def run():
print("Running MyModule.SubModuleOne.smo!")
"""
from MyModule.SubModule import smo
smo.run()
# Running MyModule.SubModuleOne.smo!
---------------------------------------------------------------------------
ImportError Traceback (most recent call last)
<ipython-input-40-c2d8d80de486> in <module>()
9 print("Running MyModule.SubModuleOne.smo!")
10 """
---> 11 from MyModule.SubModule import smo
12 smo.run()
13 # Running MyModule.SubModuleOne.smo!
ImportError: No module named 'MyModule.SubModule'
11. VII. Pythonic¶
12. VIII. Standard Libraries¶
[ ]: