Python - Foundation
-1. print format and f string, use print()
eg:
x='seven'
print('x is {}'.format(x))
print ('x is {} {}'.format (8,10))
print ('x is {1:<09} {0:>09}'.format (8,10))
a=8
b=10
x= f'seven {b} {a}'
print (x)
-2. decimal
eg:
from decimal import *
a = Decimal('.10')
b = Decimal('.30')
x = a+a+a-b
print (x) -->0.00
if no decimal, x is almost 0 but not 0 due to accuracy and precision
-3. / or //
eg:
7/3 =2.3333333333333335
7//3 =2
7%3 =1
-4. type() and id(), isinstance()
eg:
x=(1,2,3)
print (type(x))
print (id(x))
print (isinstance(x, turple))
-5. if
eg:
hungry=0
x="feed" if hungry else "not feed"
print (x)
-6. args
eg:
def kittern(*args):
if len(args):
for s in args:
print (x)
else: print "no args"
def main():
x=(1,2,3)
kittern (*x)
-7. keyword args
eg:
def kittern(**kwargs):
if len(kwargs):
for k in kwargs:
print (k, kwargs[k])
else: print "no kwargs"
def main():
x=dict(a=1,b=2,c=3)
kittern (**x)
-8. generators, yield ?
eg:
range(10)
yield
-9. decorators
eg:
def f1(f):
def f2():
print ("before")
f()
print ("after")
return f2
@f1
def f3():
print("this is f3")
f3()
-10. list comprehension
eg:
seq1=range(10)
seq2=[x *2 for x in seq if x%3!=0]
seq3=[(x,x**2) for x in seq]
seq4=[ round(pi,i) for i in seq]
seq5={x:x**2 for x in seq}
seq5={x:x**2 for x in seq}
-11. init() and str()
-12. python的各种下划线 >>https://zhuanlan.zhihu.com/p/36173202 >>https://aji.tw/python%E4%BD%A0%E5%88%B0%E5%BA%95%E6%98%AF%E5%9C%A8__%E5%BA%95%E7%B7%9A__%E4%BB%80%E9%BA%BC%E5%95%A6/ >>https://www.cnblogs.com/coder2012/p/4423356.html
-13. Exceptions
eg:
import sys
try:
x=ini('foo')
except ValueError as e:
print('caught a value err')
print(f'err:{e}')
except ZeorDivisionError:
print('caught a value err')
except:
print(f'unkonw error:' {sys.exc_info()})
else:
print('good job')
-14. raise errs
eg:
if arg1<1:
raise TypeError(f'excepted at least 1 argement')
-15. file I/O
eg:
rb, wb
rt, wt
-16. built-in function
eg:
zip()
enumerate()
-17. DB
eg:
import sqlite3
db=sqlite3.connect('db-api.db')
cur=db.cursor()
cur.execuret(""" Insert into... """
db.commit()
cur.execute("Select ...")
db.close()
-18. global vs local
-19. del, 删除的是变量,而不是数据
if __name__=='__main__':
a=1 # 对象 1 被 变量a引用,对象1的引用计数器为1
b=a # 对象1 被变量b引用,对象1的引用计数器加1
c=a #1对象1 被变量c引用,对象1的引用计数器加1
del a #删除变量a,解除a对1的引用
del b #删除变量b,解除b对1的引用
print(c) #最终变量c仍然引用1
-20. 循环 enumerate()
days=['Mon','Tue','Wed','Thu','Fri','Sat','Sun']
for i, d in enumerate(days):
print(i,d)