2 ** 10
1024
v = 100
v
100
v = "hello"
v
'hello'
s = '''
hello
asd
asd
as
'''
s
'\nhello\n\nasd\nasd\n\n\nas\n'
ls = [ 100, 42, 'test']
ls
[100, 42, 'test']
ls[1] = 43
ls
[100, 43, 'test']
t = (200, 'demo')
t
(200, 'demo')
type(t)
tuple
ls
[100, 43, 'test']
ls = ['a', 'foo', 'bar', 'baz', 'qaz']
ls
['a', 'foo', 'bar', 'baz', 'qaz']
ls[0:-1]
['a', 'foo', 'bar', 'baz']
s = 'foo, 2, 3, 4, 5, 6'
s
'foo, 2, 3, 4, 5, 6'
s.split(', ')
['foo', '2', '3', '4', '5', '6']
', '.join(['foo', 'bar', '1231313'])
'foo, bar, 1231313'
'Hello {0}! i am {1}'.format('Bob', 'Iblis')
'Hello Bob! i am Iblis'
list
operations¶list.append()
list.pop()
ls
['a', 'foo', 'bar', 'baz', 'qaz']
ls.append('Bob')
ls.pop()
'Bob'
ls
['a', 'foo', 'bar', 'baz', 'qaz']
t
(200, 'demo')
t.append('ads')
------------------------------------------------------- AttributeError Traceback (most recent call last) <ipython-input-40-1ade54080318> in <module>() ----> 1 t.append('ads') AttributeError: 'tuple' object has no attribute 'append'
x = 3
y = -4
x, y
(3, -4)
x, y = y, x # swap them!
x, y
(-4, 3)
x, y = 2, 5
x, y
(2, 5)
s1, s2 = 'Hello ', 'World'
s3 = s1 + s2
s3
'Hello World'
ls1, ls2 = ['Bob', 'Alice'], [42, 43]
ls1
['Bob', 'Alice']
ls2
[42, 43]
ls1 + ls2
['Bob', 'Alice', 42, 43]
ls1
['Bob', 'Alice']
ls2
[42, 43]
d = {
'bob': 12,
'foo': 'bar',
'ls': [1, 2, 3]
}
d
{'bob': 12, 'foo': 'bar', 'ls': [1, 2, 3]}
d['ls'][-1]
3
d['strange']
------------------------------------------------------- KeyError Traceback (most recent call last) <ipython-input-66-e894436bd742> in <module>() ----> 1 d['strange'] KeyError: 'strange'
d
{'bob': 12, 'foo': 'bar', 'ls': [1, 2, 3]}
d['bob'] = 123
d
{'bob': 123, 'foo': 'bar', 'ls': [1, 2, 3]}
d['strange'] = 42
d
{'bob': 123, 'foo': 'bar', 'ls': [1, 2, 3], 'strange': 42}
d.items()
dict_items([('ls', [1, 2, 3]), ('strange', 42), ('bob', 123), ('foo', 'bar')])
s = set([1, 2,3, 1, 1])
s
{1, 2, 3}
ls
['a', 'foo', 'bar', 'baz', 'qaz']
ls = [1, 2,5, 100, 25, 47]
sorted(ls)
[1, 2, 5, 25, 47, 100]
ls1 = [1, 2, 3, 12]
ls2 = ['foo', 'bob', 'bar', 'kk']
dict(zip(ls1, ls2))
{1: 'foo', 2: 'bob', 3: 'bar', 12: 'kk'}
score = 20
if score >= 60:
print('讚')
# ....
# ....
else:
print('fail')
fail
for i in ['a', 'b', 'c']:
print(i)
a b c
iter 從 0 到 10
for i in range(10):
print(i)
0 1 2 3 4 5 6 7 8 9
points = [
(0, 0),
(3, -4),
(5, 2)
]
for p in points:
print(p)
(0, 0) (3, -4) (5, 2)
for x, y in points[2:1:-1]:
print(x, y)
5 2 3 -4 0 0
d
{'bob': 123, 'foo': 'bar', 'ls': [1, 2, 3], 'strange': 42}
d.items()
dict_items([('ls', [1, 2, 3]), ('strange', 42), ('bob', 123), ('foo', 'bar')])
for key, val in d.items():
print('{0} is {1}'.format(key, val))
ls is [1, 2, 3] strange is 42 bob is 123 foo is bar
for i in [1, 3, 5]:
if i % 2 == 0:
pass
else:
print('no even number')
no even number
if True:
...
else:
2
type(...)
ellipsis
def f(x):
return x ** 2 + 1
f(100)
10001
def g():
print('Hello')
g()
Hello
ret = g()
Hello
type(ret)
NoneType
def f(*big_list):
ret = 1
for i in big_list:
ret = ret * i
return ret
f(1)
1
f(1,2,3,4,5)
120
def f(*big_list, **big_dictionary):
print(big_list)
print(big_dictionary)
f(1, 2, 3)
(1, 2, 3) {}
f(1, 2, 3, x=1, foo='100')
(1, 2, 3) {'x': 1, 'foo': '100'}
(lambda x: x** 2 + 1)(100)
10001
a = [1, 2, 3]
b = [1, 2, 3]
b is a, b == a
(False, True)
0 <= 60 <= 100
True
ls = [1, 2, 3, 42, 100 ,51]
sum(ls)
199
min(ls)
1
max(ls)
100
len(ls)
6
[2 * x for x in (1, 2, 3, 4, 6)]
[2, 4, 6, 8, 12]
{
key: val for key,val in (('foo', 1), ('bar', 42))
}
{'bar': 42, 'foo': 1}
list(
map(lambda x: 2 * x, # f(x) = 2x
(1, 2, 3, 4, 6))
)
[2, 4, 6, 8, 12]
def f(x):
return 2 * x
list(
map(f,
(1, 2, 3, 4, 6)
)
)
[2, 4, 6, 8, 12]
class Circle:
def __init__(self, radius):
self.radius = radius
self.name = 'XD'
@property
def area(self):
return self.radius ** 2 * 3.14
c = Circle(5)
c # this is instance
<__main__.Circle at 0x103a57cf8>
c.radius
5
c.area # c.radius * 2 * 3.14
78.5
def greeting(func):
def wrapper(user):
print('Hello {}'.format(user))
func(user + '5555')
return wrapper
def f(user):
print('User: {}'.format(user))
f = greeting(f)
f('Bob')
Hello Bob User: Bob5555
import decorators
decorators.greeting
<function decorators.greeting>
@decorators.greeting
def g(user):
print('aaaaaaa')
g('Alice')
Hello Alice aaaaaaa
decorators
<module 'decorators' from '/Users/iblis/tmp/decorators.py'>
import math
math
<module 'math' from '/usr/local/Cellar/python3/3.5.0/Frameworks/Python.framework/Versions/3.5/lib/python3.5/lib-dynload/math.cpython-35m-darwin.so'>
math.pi
3.141592653589793
help(math)
Help on module math: NAME math MODULE REFERENCE http://docs.python.org/3.5/library/math The following documentation is automatically generated from the Python source files. It may be incomplete, incorrect or include features that are considered implementation detail and may vary between Python implementations. When in doubt, consult the module reference at the location listed above. DESCRIPTION This module is always available. It provides access to the mathematical functions defined by the C standard. FUNCTIONS acos(...) acos(x) Return the arc cosine (measured in radians) of x. acosh(...) acosh(x) Return the inverse hyperbolic cosine of x. asin(...) asin(x) Return the arc sine (measured in radians) of x. asinh(...) asinh(x) Return the inverse hyperbolic sine of x. atan(...) atan(x) Return the arc tangent (measured in radians) of x. atan2(...) atan2(y, x) Return the arc tangent (measured in radians) of y/x. Unlike atan(y/x), the signs of both x and y are considered. atanh(...) atanh(x) Return the inverse hyperbolic tangent of x. ceil(...) ceil(x) Return the ceiling of x as an int. This is the smallest integral value >= x. copysign(...) copysign(x, y) Return a float with the magnitude (absolute value) of x but the sign of y. On platforms that support signed zeros, copysign(1.0, -0.0) returns -1.0. cos(...) cos(x) Return the cosine of x (measured in radians). cosh(...) cosh(x) Return the hyperbolic cosine of x. degrees(...) degrees(x) Convert angle x from radians to degrees. erf(...) erf(x) Error function at x. erfc(...) erfc(x) Complementary error function at x. exp(...) exp(x) Return e raised to the power of x. expm1(...) expm1(x) Return exp(x)-1. This function avoids the loss of precision involved in the direct evaluation of exp(x)-1 for small x. fabs(...) fabs(x) Return the absolute value of the float x. factorial(...) factorial(x) -> Integral Find x!. Raise a ValueError if x is negative or non-integral. floor(...) floor(x) Return the floor of x as an int. This is the largest integral value <= x. fmod(...) fmod(x, y) Return fmod(x, y), according to platform C. x % y may differ. frexp(...) frexp(x) Return the mantissa and exponent of x, as pair (m, e). m is a float and e is an int, such that x = m * 2.**e. If x is 0, m and e are both 0. Else 0.5 <= abs(m) < 1.0. fsum(...) fsum(iterable) Return an accurate floating point sum of values in the iterable. Assumes IEEE-754 floating point arithmetic. gamma(...) gamma(x) Gamma function at x. gcd(...) gcd(x, y) -> int greatest common divisor of x and y hypot(...) hypot(x, y) Return the Euclidean distance, sqrt(x*x + y*y). isclose(...) is_close(a, b, *, rel_tol=1e-09, abs_tol=0.0) -> bool Determine whether two floating point numbers are close in value. rel_tol maximum difference for being considered "close", relative to the magnitude of the input values abs_tol maximum difference for being considered "close", regardless of the magnitude of the input values Return True if a is close in value to b, and False otherwise. For the values to be considered close, the difference between them must be smaller than at least one of the tolerances. -inf, inf and NaN behave similarly to the IEEE 754 Standard. That is, NaN is not close to anything, even itself. inf and -inf are only close to themselves. isfinite(...) isfinite(x) -> bool Return True if x is neither an infinity nor a NaN, and False otherwise. isinf(...) isinf(x) -> bool Return True if x is a positive or negative infinity, and False otherwise. isnan(...) isnan(x) -> bool Return True if x is a NaN (not a number), and False otherwise. ldexp(...) ldexp(x, i) Return x * (2**i). lgamma(...) lgamma(x) Natural logarithm of absolute value of Gamma function at x. log(...) log(x[, base]) Return the logarithm of x to the given base. If the base not specified, returns the natural logarithm (base e) of x. log10(...) log10(x) Return the base 10 logarithm of x. log1p(...) log1p(x) Return the natural logarithm of 1+x (base e). The result is computed in a way which is accurate for x near zero. log2(...) log2(x) Return the base 2 logarithm of x. modf(...) modf(x) Return the fractional and integer parts of x. Both results carry the sign of x and are floats. pow(...) pow(x, y) Return x**y (x to the power of y). radians(...) radians(x) Convert angle x from degrees to radians. sin(...) sin(x) Return the sine of x (measured in radians). sinh(...) sinh(x) Return the hyperbolic sine of x. sqrt(...) sqrt(x) Return the square root of x. tan(...) tan(x) Return the tangent of x (measured in radians). tanh(...) tanh(x) Return the hyperbolic tangent of x. trunc(...) trunc(x:Real) -> Integral Truncates x to the nearest Integral toward 0. Uses the __trunc__ magic method. DATA e = 2.718281828459045 inf = inf nan = nan pi = 3.141592653589793 FILE /usr/local/Cellar/python3/3.5.0/Frameworks/Python.framework/Versions/3.5/lib/python3.5/lib-dynload/math.cpython-35m-darwin.so
def f(ls):
try:
print(ls[50] ** 2)
except Exception as e:
print(e)
print('Oops!')
f([1,2 ,3])
list index out of range Oops!
def gen():
print('line 1')
...
yield 100
print('line 200')
yield 42
for i in gen():
print('############# {} ##########'.format(i))
line 1 ############# 100 ########## line 200 ############# 42 ##########
import decorator
decorator
<module 'decorator' from '/Users/iblis/tmp/.venv/lib/python3.5/site-packages/decorator.py'>