#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])))
>>> 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")