liyeho 发表于 2017-4-30 12:00:09

Python Tutorial 笔记2

Module
  1. 基础
  

#fib.py
def fib2(n):
rst = []
a, b = 0 ,1
while b < n:
rst.append(b)
a, b = b, a+b
return rst
if __name__ == '__main__':
import sys
print(fib2(int(sys.argv)))


>>> import fib
>>> fib.fib2(2000)

>>> fib.__name__
'fib'
>>>
  2. Module 搜索路径
  sys.path and PYTHONPATH 
  3. dir() function
   

 Input and Output
  1.  String format

>>> print('The story of {0}, {1}, and {other}.'.format('Bill', 'Manfred',other='Georg'))
The story of Bill, Manfred, and Georg.
>>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 7678}
>>> for name, phone in table.items():
...   print('{0:10} ==> {1:10d}'.format(name, phone))
...
Jack       ==>       4098
Dcab       ==>       7678
Sjoerd   ==>       4127
>>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678}
>>> print('Jack: {0:d}; Sjoerd: {0:d}; '
'Dcab: {0:d}'.format(table))
Jack: 4098; Sjoerd: 4127; Dcab: 8637678
>>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678}
>>> print('Jack: {Jack:d}; Sjoerd: {Sjoerd:d}; Dcab: {Dcab:d}'.format(**table))
Jack: 4098; Sjoerd: 4127; Dcab: 8637678

  老的方式:

>>> import math
>>> print('The value of PI is approximately %5.3f.' % math.pi)
The value of PI is approximately 3.142.

  2. 文件操作

L = []
with open('input.txt', 'r') as f:
while True:
tmp = f.readline()
if tmp == '':
break
if tmp.find("小志") == 0:
L.append(tmp)
with open('output.txt', 'w') as f:
for line in L:
f.write(line)

  3. 持久化

import pickle
l=
d={"one":1, "two":2, "three":3}
print("list is:", end='')
print(l)
print("dict is:", end='')
print(d)
with open('save.txt', 'wb') as f:
pickle.dump(l, f)
pickle.dump(d, f)
with open('save.txt', 'rb') as f:
lst = pickle.load(f)
print(lst)
dct = pickle.load(f)
print(dct)                           
 Errors and Exceptions

import sys
try:
a = 1 / (int(sys.argv))
print(a)
except ZeroDivisionError as zderr:
print(zderr)
raise
else:
print("no exception")
finally:
print("end")
页: [1]
查看完整版本: Python Tutorial 笔记2