`

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[1])))

 

>>> import fib
>>> fib.fib2(2000)
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597]
>>> 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[Jack]:d}; Sjoerd: {0[Sjoerd]:d}; '
          'Dcab: {0[Dcab]: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=[1,2,3]
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[1]))
  print(a)
except ZeroDivisionError as zderr:
  print(zderr)
  raise
else:
  print("no exception")
finally:
  print("end")             

 

1
0
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics