学习小笔记

2019-02-20  本文已影响1人  10xjzheng
from collections import deque
#文件读写
f = open('./test.txt', 'w+')
f.write('terrible and fuck\n')
f.write('aaa and eee')
f = open('./test.txt', 'r')
print(f.readline())
f.close()

#函数
def fib(n):
    """Print a Fibonacci series up to n"""
    a, b = 0, 1
    while a < n :
        print (a, end=' ')
        a, b = b, a+b
    print ()
fib(2000)

#参数,不定参数,关键字参数
def ask_ok(prompt, retries=4, complaint='Yes or no,please!'):
    while True:
        ok = input(prompt)
        if ok in ('y','ye','yes'):
            return True
        if ok in('n', 'no', 'nope'):
            return False
        if retries < 0:
            raise OSError('uncooperative user')
        print(complaint)
#ask_ok('Do you really want to quit?')

def parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'):
    print("--This parrot would'n t", action, end=' ')
    print("if you put", voltage, 'volts through it')
    print('--Lovely plumage, the', type)
    print("-- It's", state, "!")

parrot(voltage=1000, action='VOOOOM')
parrot('a thousand', type='Red')

def cheeseshop(kind, *arguments, **keywords):
    print("--Do you have any", kind, '?')
    print("--I'm sorry, we're all out of", kind)
    print("-" * 40)
    for arg in arguments:
        print(arg)
    print("-" * 40)
    keys = sorted(keywords.keys())
    for kw in keys:
        print(kw, ":", keywords[kw])

cheeseshop("Limburger", "It's very runny, sir.",
           "It's really very runny, sir.",
           shopkeeper='Michael Palin',
           client='John Cheese',
           sketch='Cheese Shop Sketch')

def concat(*args, sep='/'):
    return sep.join(args)

print(concat('earth', 'mars', 'venus'))

#列表
a = [333, 66.23, 333, 444, 222, 111]
print(a.count(333), a.count(222))

a.insert(3, -1)
a.append(330)
print(a)
a.remove(333)
print(a)
a.reverse()
print(a)
a.sort()
print(a)
print(a.pop())
#栈
stack = [3, 4, 5]
stack.append(6);
print(stack.pop())

#队列
queue = deque(['Eric', 'John', 'Michael'])
queue.append('Terry')
queue.append('Graham')
print(queue.popleft())
print(queue)

#列表推倒式
squares = []
for x in range(10):
    squares.append(x**2)
print(squares)

squares = list(map(lambda x:x**2, range(10)))
print(squares)

squares = [x**2 for x in range(10)]
print(squares)

#嵌套的列表推倒式
matrix = [
    [1, 2, 3, 4],
    [5, 6, 7, 8],
    [9, 10, 11, 12]
]
newMatrix = [[row[i] for row in matrix] for i in range(4)]
print(newMatrix)

#del 语句
del matrix[0]
print(matrix)

#元组和序列,一个元组由数个逗号分隔的值组成
t = 12345, 54345, 'hello'
print(t[0])
u = t, (2,3,4,5)
print(u)

#集合
tel = {'jack': 323, 'sage':444}
tel['guido'] = 466
print(tel)

keys = list(tel.keys())
print(keys)
keys = sorted(keys)
print(keys)

#循环技巧
##--字典--
knights = {'gall': 'the pure', 'robin': 'the brave'}
for k, v in knights.items():
    print(k,v)
#--序列--
for i, v in enumerate(['tic', 'tac', 'toe']):
    print(i, v)
#--同时循环两个或更多的序列
questions = ['name', 'quest', 'favorite color']
answers = ['lancelot', 'the holy grail', 'blue']
for q, a in zip(questions, answers):
    print('what is your {0}? It is {1}' . format(q, a))

#逆向循环
for i in reversed(range(1, 10, 2)):
    print(i)
#深入条件控制
##while和if可以包含任意操作, in ,not in , is ,is not, and, or


#模块
import module
module.fib(2000)
print()
print(dir()) #注意该列表列出了所有类型的名称:变量,模块,函数,等等。
if __name__ == "__main__":
    print('main')

#exception
while True:
    try:
        x = 10
        #x = int(input('Please enter a number:'))
        break
    except ValueError:
        print('Oops! That was no valid number, Try again..')

import sys
try:
    f = open('test.txt')
    s = f.readline()
    i = int(s.strip())
except OSError as err:
    print('OS error: {0}' . format(err))
except ValueError:
    print('Could not convert data to an integer')
except:
    print('Unexpected error:', sys.exc_info()[0])
    raise

try:
    raise NameError('hi there')
except NameError as err:
    print(err)

#自定义异常
class MyError(Exception):
    def __init__(self, value):
        self.value = value
    def __str__(self):
        return repr(self.value)

try:
    raise MyError(2*2)
except MyError as e:
    print('my exception occurred, value:', e.value)

#raise MyError('oops')

#else 语句
def divide(x, y):
    try:
        result = x/y
    except ZeroDivisionError:
        print('division by zero')
    else:
        print('result is', result)
    finally:
        print('execution finally clause')

divide(2, 1)

#作用域和命名空间示例
def scope_test():
    def do_local():
        spam = 'local spam'
    def do_nonlocal():
        nonlocal spam
        spam = 'nonlocal spam'
    def do_global():
        global spam
        spam = 'global spam'
    spam = 'test spam'
    do_local()
    print('After local assignment:', spam)
    do_nonlocal()
    print('After nonlocal assignment:', spam)
    do_global()
    print('After global assignment:', spam)

scope_test()
print('In global scope:', spam)

#类对象
class MyClass:
    """A simple example class"""
    i = 12345
    def __init__(self):
        self.i = 8888
    def f(self):
        return self.i
obj = MyClass()
print(obj.f())

class Complex:
    def __init__(self, realpart, imagpart):
        self.r = realpart
        self.i = imagpart
cc = Complex(3,43)
print(cc.i, cc.r)

#类属性的任何函数对象都为那个类的实例定义了一个方法。函数定义代码不一定非得定义在类中:也可以将一个函数对象赋值给类中的一个局部变量。例如:
def f1(self, x, y):
    return min(x, x+y)

class C:
    f = f1
    def g(self):
        return 'hello world'
    h = g
ccc = C()
print(ccc.f(2, 4))

#继承
#函数 isinstance() 用于检查实例类型: isinstance(obj, int) 只有在 obj.__class__ 是 int 或其它从 int 继承的类型
#函数 issubclass() 用于检查类继承: issubclass(bool, int) 为 True,因为 bool 是 int 的子类
#super() 可以动态的改变解析顺序。这个方式可见于其它的一些多继承语言,类似 call-next-method,比单继承语言中的 super 更强大 。
#多继承
class Base1:
    def b(self):
        return False

class Base2:
    def b(self):
        return False

class DerivedClassName(Base1, Base2):
    ccc = 'cccc'
    def f(self):
        return True
    #私有变量
    __update = 'aaa'

dd = DerivedClassName()
print(dd.ccc)

#迭代器
for element in [1, 2, 3]:
    print(element)
for element in (1, 2, 3):
    print(element)
for key in {'one':1, 'two':2}:
    print(key)
for char in "123":
    print(char)
for line in open("test.txt"):
    print(line, end='')

#生成器
sum(i*i for i in range(10))
xvec = [10, 20, 30]
yvec = [7, 5, 3]
sum(x*y for x,y in zip(xvec, yvec))

#标准库
#1 操作系统
import os
print()
print(os.getcwd())

#2 文件通配符
import glob
print(glob.glob('*.py'))

#3 命令行参数
import sys
print(sys.argv)

#4 错误输出重定向和程序终止
#sys.stderr.write('warning, log file not found')

#5 字符串正则匹配
import re
print(re.findall(r'\bf[a-z]*', 'which foot or hand fell fastest'))

#6 数学
import math
print(math.cos(math.pi / 4.0))

import random
print(random.choice(['apple', 'pear', 'banana']))

#7 互联网访问
from urllib.request import urlopen
for line in urlopen('http://www.baidu.com'):
    line = line.decode('utf-8')
    if 'EST' in line or 'EDT' in line:
        print(line)

#日期和时间
from datetime import date
now = date.today()
print(now)

#数据压缩
import zlib
s = b'witch which has which witches wrist watch'
print(len(s))
t = zlib.compress(s)
print(len(t))
上一篇下一篇

猜你喜欢

热点阅读