In [20]:
    
import this
    
    
In [2]:
    
## integer
a = 1
b = 0x10            # 16
print(type(a))      # <class 'int'>
    
    
In [3]:
    
## float
c = 1.2
d = .5              # 0.5
g = .314e1          # 3.14
print(type(g))      # <class 'float'>
    
    
In [4]:
    
## complex
e = 1+2j
f = complex(1, 2)
print(type(e))      # <class 'complex'>
print(f == e)       # True
    
    
In [21]:
    
## Operators: + - * / ** // %
print(1 + 1)
print(2 - 2)
print(3 * 3)
print(5 / 4)
print(2 ** 10)
print(5 // 4)
print(5 % 4)
    
    
In [27]:
    
## Casting
### Integer -> Float
print(float.__doc__)
print(float(3))
print(3 / 1)
print(float("3.14"))
    
    
In [28]:
    
### Float -> Integer
print(int.__doc__)
    
    
In [41]:
    
print(int(3.14))               # 3
print(int("3", base = 10))     # 3
print(int("1010", base = 2))   # 10
print(int("0b1010", base = 0)) # 10
    
    
In [5]:
    
s1 = '🐶\n'
s2 = "Dogge's home"
s3 = """
Hello,
Dogge!
"""
print(type(s1))     # <class 'str'>
print("%s, %s, %s" % (s1, s2, s3))
    
    
In [6]:
    
## Length
print(len(s1))      # 2
    
    
In [7]:
    
## Slicing
s = '学而时习之'
print('{0}:{1}'.format(s[0], s[-2]))    # 学:习
    
    
In [48]:
    
## Operator: +
print("abc" + "." + "xyz")
    
    
In [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'}))
    
    
In [8]:
    
# Byte
## 0-255/x00-xff
byt = b'abc'
print(type(byt))    # <class 'bytes'>
print(byt[0] == 'a')# False
print(byt[0] == 97) # True
    
    
In [9]:
    
## Length
print(len(byt))     # 3
    
    
In [10]:
    
True
False
print(type(True))   # <class 'bool'>
    
    
In [11]:
    
print(None is None) # True
print(type(None))   # <class 'NoneType'>
    
    
In [12]:
    
l = ['python', 3, 'in', 'one']
print(type(l))      # <class 'list'>
    
    
In [13]:
    
## Length
print(len(l))       # 4
    
    
In [14]:
    
## Slicing
print(l[0])         # 'python'
print(l[-1])        # 'one'
print(l[1:-1])      # [3, 'in']
    
    
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', '!', '!']
    
    
In [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', '!']
    
    
In [17]:
    
print(l.index('pic'))       # 2
    
    
In [18]:
    
tp = (1, 2, 3, [4, 5])
print(type(tp)) # <class 'tuple'>
    
    
In [19]:
    
## Length
print(len(tp))  # 4
print(tp[2])    # 3
tp[3][1] = 6
print(tp)       # (1, 2, 3, [4, 6])
    
    
In [20]:
    
## Single element
tp = (1, )      # Not tp = (1)
print(tp)
    
    
In [21]:
    
## Assign multiple values at once
v = (3, 2, 'a')
(c, b, a) = v
print(a, b, c)  # a 2 3
    
    
In [22]:
    
st = {'s', 'e', 'T'}
print(type(st)) # <class 'set'>
    
    
In [23]:
    
## Length
print(len(st))  # 3
    
    
In [24]:
    
## Empty
st = set()
print(len(st))  # 0
    
    
In [25]:
    
st = {}
print(type(st)) # <class 'dict'>
    
    
In [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)
    
    
In [2]:
    
dic = {}
print(type(dic))    # <class 'dict'>
dic = {'k1': 'v1', 'k2': 'v2'}
print(dic)
    
    
In [3]:
    
## Length
print(len(dic))     # 2
    
    
In [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
    
    
In [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")
    
    
for
In [49]:
    
for i in "Hello":
    print(i)
    
    
while
In [8]:
    
prod = 1
i = 1
while i < 10:
    prod = prod * i
    i += 1
print(prod)
    
    
In [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
    
    
In [57]:
    
## continue
for num in range(2, 10):
    if num % 2 == 0:
        print("Found an even number", num)
        continue
    print("Found a number", num)
    
    
List
In [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)
    
    
Set
In [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)
    
    
Dict
In [15]:
    
ls = {s: len(s) for s in ["Python", "Javascript", "Golang"]}
print(ls)
sl = {v: k for k, v in ls.items()}
print(sl)
    
    
In [30]:
    
python = iter("Python")
print(python)
for i in python:
    print(i)
    
    
In [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)
    
    
In [64]:
    
def f():
    """return 'Hello, World!'"""
    return "Hello, World!"
print(f())
print(f.__doc__)
    
    
In [69]:
    
## default arguments
def f(name = "World"):
    """return 'Hello, $name'"""
    return "Hello, {}!".format(name)
print(f())
print(f("Python"))
    
    
In [74]:
    
## keyword arguments
def f(v, l = "Python"):
    """return '$v, $l'"""
    return "{}, {}!".format(v, l)
print(f("Hello"))
print(f("Bye", "C/C++"))
    
    
In [102]:
    
## arbitrary arguments
def f(*args, con = " & "):
    print(isinstance(args, tuple))
    print("Hello", con.join(args))
f("Python", "C", "C++", con = "/")
    
    
In [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")
    
    
In [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)
    
    
In [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()
    
    
In [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
    
    
In [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!
    
    
In [19]:
    
class Animal:
    pass
class Human:
    pass
a = Animal()
h = Human()
print(isinstance(a, Animal))
print(isinstance(h, Animal))
    
    
In [22]:
    
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("汪汪!")
d = Dog()
d.fly()
d.bark()
    
    
In [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!
    
    
In [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)
    
    
In [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!
    
    
In [ ]: