Python初探及入门

由于无意间体验了Python的便捷和强大,花了2天时间把Python教程看完并学习了一遍,着实感受到了Python语言的优雅和强大。

附上我的学习练习过程,文件内容是倒序,直接保存文件为test.py,附上权限 $ chmod a+x ./test.py 即可在命令窗口中直接运行此文件,注意路径。
tip:并不是所有的教程内容都有在文档中体现;

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import math
from functools import reduce
import functools
from operator import itemgetter
import types
from enum import Enum,unique
from multiprocessing import Pool
import os, time, random,threading
import pickle
import json
from multiprocessing import Process
import re
from datetime import datetime,timedelta
from collections import namedtuple,deque,Counter
import base64,struct,hashlib,itertools
from contextlib import contextmanager,closing
from urllib.request import urlopen
from urllib import request,parse
import socket,asyncio


# Done!

# async def hello():
#     print("Hello world!")
#     r = await asyncio.sleep(1)
#     print("Hello again!")
# loop = asyncio.get_event_loop()
# tasks = [hello()]
# loop.run_until_complete(asyncio.wait(tasks))
# loop.close()

# def consumer():
#   r=''
#   while True:
#       n = yield r
#       if not n:
#           return
#       print('consumer get:',n)
#       r = '200 ok'
# def produce(c):
#   c.send(None)
#   n = 0
#   while n < 5:
#       n = n + 1
#       print('produce n:',n)
#       r = c.send(n)
#       print('consumer return:',r)
#   c.close()
# c = consumer();
# produce(c)

# s =socket.socket(socket.AF_INET,socket.SOCK_STREAM)
# s.connect(('www.sina.com.cn',80))
# s.send(b'GET / HTTP/1.1\r\nHost: www.sina.com.cn\r\nConnection: close\r\n\r\n')
# buffer = []
# while True:
#   d = s.recv(1024)
#   if d:
#       buffer.append(d)
#   else:
#       s.close()
#       break;
# data = b''.join(buffer)
# print(data)

# email = input('Email: ')
# passwd = input('Password: ')
# login_data = parse.urlencode([
#     ('username', email),
#     ('password', passwd),
#     ('entry', 'mweibo'),
#     ('client_id', ''),
#     ('savestate', '1'),
#     ('ec', ''),
#     ('pagerefer', 'https://passport.weibo.cn/signin/welcome?entry=mweibo&r=http%3A%2F%2Fm.weibo.cn%2F')
# ])
# req = request.Request('https://passport.weibo.cn/sso/login')
# req.add_header('Origin', 'https://passport.weibo.cn')
# req.add_header('User-Agent', 'Mozilla/6.0 (iPhone; CPU iPhone OS 8_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/8.0 Mobile/10A5376e Safari/8536.25')
# req.add_header('Referer', 'https://passport.weibo.cn/signin/login?entry=mweibo&res=wel&wm=3349&r=http%3A%2F%2Fm.weibo.cn%2F')
# with request.urlopen(req, data=login_data.encode('utf-8')) as f:
#     print('Status:', f.status, f.reason)
#     for k, v in f.getheaders():
#         print('%s: %s' % (k, v))
#     print('Data:', f.read().decode('utf-8'))

# with request.urlopen('https://api.douban.com/v2/book/2129650') as f:
#   data = f.read()
#   for k,v in f.getheaders():
#       print(k,v)
#   print(data.decode('utf-8'))

# with closing(urlopen('http://www.baidu.com')) as page:
#   for line in page:
#       print(line)

# @contextmanager
# def tag(name):
#     print("<%s>" % name)
#     yield
#     print("" % name)
# with tag("h1"):
#     print("hello")
#     print("world")

# class Query(object):
#     def __init__(self, name):
#         self.name = name
#     def query(self):
#         print('Query info about %s...' % self.name)
# @contextmanager
# def create_query(name):
#   print('begin')
#   q = Query(name)
#   yield q
#   print('end!')
# with create_query('testname') as b:
#   b.query()

# for c in itertools.chain('ABC','XYZ'):
#   print(c)

# a = 'how to use md5 in python hashlib?'.encode('utf-8')
# md5 = hashlib.md5()
# md5.update(a)
# print(md5.hexdigest())
# sha1 = hashlib.sha1()
# sha1.update(a)
# print(sha1.hexdigest())

# a = struct.pack('>I',10240099)
# print(a)
# b = struct.unpack('>IH', b'\xf0\xf0\xf0\xf0\x80\x80')
# print(b)

# a = base64.b64encode(b'binary\x00string')
# print(a)
# b = base64.urlsafe_b64encode(b'i\xb7\x1d\xfb\xef\xff')
# print(b)

# c = Counter()
# for ch in 'programming':
#   c[ch]  = c[ch] +1
# print(c)

# q = deque(['a','b','c'])
# print(q)
# q.append('x')
# q.appendleft('y')
# print(q)

# a = namedtuple('Point',['x','y'])
# p = a(1,2)
# print(p.x,p.y)

# now = datetime.now()
# add = now+ timedelta(hours = 10)
# print(add)
# de = add - timedelta(hours = 5)
# print(de)

# now = datetime.now()
# print(now)
# t = now.timestamp()
# print(t)
# ts = datetime.fromtimestamp(t)
# print(ts)
# tf = ts.strftime('%a,%b %d %H:%M')
# print(tf)

# m = re.match(r'^(\d{3})-(\d{3,8})$','010-12345')
# print(m)
# print(m.group(1))

# ---------0305-正则表达式-------

# # 假定这是你的银行存款:
# balance = 0
# lock = threading.Lock()
# def change_it(n):
#     # 先存后取,结果应该为0:
#     global balance
#     balance = balance + n
#     balance = balance - n

# def run_thread(n):
#     for i in range(100000):
#       lock.acquire()
#       try:
#           change_it(n)
#       finally:
#           lock.release()

# t1 = threading.Thread(target=run_thread, args=(5,))
# t2 = threading.Thread(target=run_thread, args=(8,))
# t1.start()
# t2.start()
# t1.join()
# t2.join()
# print(balance)

# # 新线程执行的代码:
# def loop():
#     print('thread %s is running...' % threading.current_thread().name)
#     n = 0
#     while n < 5:
#         n = n + 1
#         print('thread %s >>> %s' % (threading.current_thread().name, n))
#         time.sleep(1)
#     print('thread %s ended.' % threading.current_thread().name)

# print('thread %s is running...' % threading.current_thread().name)
# t = threading.Thread(target=loop, name='LoopThread')
# t.start()
# t.join()
# print('thread %s ended.' % threading.current_thread().name)

# def long_time_task(name):
#     print('Run task %s (%s)...' % (name, os.getpid()))
#     start = time.time()
#     time.sleep(random.random() * 3)
#     end = time.time()
#     print('Task %s runs %0.2f seconds.' % (name, (end - start)))

# if __name__=='__main__':
#     print('Parent process %s.' % os.getpid())
#     p = Pool(4)
#     for i in range(5):
#         p.apply_async(long_time_task, args=(i,))
#     print('Waiting for all subprocesses done...')
#     p.close()
#     p.join()
#     print('All subprocesses done.')

# def run_proc(name):
#   print('run child progress %s (%s)...' % (name, os.getpid()))
# if __name__=='__main__':
#   print('Parent process %s.' % os.getpid())
#   p = Process(target = run_proc,args=('test',))
#   print('Child process will start.')
#   p.start()
#   p.join()
#   print('Child process end.')

# class Student(object):
#     def __init__(self, name, age, score):
#         self.name = name
#         self.age = age
#         self.score = score
# s = Student('Bob', 20, 88)
# json_str = json.dumps(s,default=lambda obj:obj.__dict__)
# print(json_str)
# def dict2student(d):
#     return Student(d['name'], d['age'], d['score'])
# stu = json.loads(json_str,object_hook = dict2student)
# print(stu.name)

# d= dict(name='Bob', age=20, score=88)
# j = json.dumps(d)
# print(j)

# d= dict(name='Bob', age=20, score=88)
# d['name']="smith"
# f =open('hello.txt','wb')
# pickle.dump(d,f)
# f.close
# f= open('hello.txt','rb')
# d = pickle.load(f)
# f.close
# print(d)

# print(os.name)

# with open('hello.txt','w') as f:
#   b = ' this is test'
#   f.write(b)
# with open('hello.txt','r') as f:
#   a = f.read()
#   print(a)

# @unique
# class Weekday(Enum):
#     Sun = 0 # Sun的value被设定为0
#     Mon = 1
#     Tue = 2
#     Wed = 3
#     Thu = 4
#     Fri = 5
#     Sat = 6
# print(Weekday.Sun.value)

# Month = Enum('Month',('JAN','FEB','MAR'))
# for name,member in Month.__members__.items():
#   print(name,'=>',member,',',member.value)
# for a in Month.__members__.items():
#   print(a)

# class Student(object):
#     @property
#     def score(self):
#         return self._score
#     @score.setter
#     def score(self, value):
#         if not isinstance(value, int):
#             raise ValueError('score must be an integer!')
#         if value < 0 or value > 100:
#             raise ValueError('score must between 0 ~ 100!')
#         self._score = value
# s = Student()
# s.score = 60
# print('s.score =', s.score)
# # ValueError: score must between 0 ~ 100!
# # s.score = 9999

# class Student(object):
#     __slots__ = ('name', 'age') # 用tuple定义允许绑定的属性名称
#     def __init__(self,name):
#       self.name = name
#     def test():
#       print('test')
# Student.test()
# stu = Student("etst11")
# print(stu.name)

# class Student(object):
#     name = 'Student'
# stu = Student()
# print(stu.name)
# print(Student.name)

# print(dir('ABC'))

# def fn():
#   pass
# print(type(fn)==types.FunctionType)

# class Animal(object):
#     def run(self):
#         print('Animal is running...')
# class Dog(Animal):
#   def run(self):
#       print('Dog is running')
# dog = Dog()
# dog.run()     

# class student(object):
#   """docstring for student"""
#   def __init__(self, name,score):
#       self.name = name
#       self.score =score
#   def print_score(self):
#       print('%s %s '%(self.name,self.score))
# bart = student('bart sime',45)
# bart.print_score()


# 第三方库:图片处理Pillow,MySQL的驱动:mysql-connector-python,用于科学计算的NumPy库:numpy,用于生成文本的模板工具Jinja2

# int2 = functools.partial(int,base = 2)
# a = int2('1000')
# print(a)

# def log(text):
#     def decorator(func):
#         def wrapper(*args, **kw):
#             print('%s %s():' % (text, func.__name__))
#             return func(*args, **kw)
#         return wrapper
#     return decorator
# @log('execute')
# def now():
#   print('now time')
# now()

# l = list(map(lambda x: x * x, [1, 2, 3, 4, 5, 6, 7, 8, 9]))
# print(l)

# students = [('Bob', 75), ('Adam', 92), ('Bart', 66), ('Lisa', 88)]
# print(sorted(students,key = itemgetter(0)))

# l = sorted(['bob', 'about', 'Zoo', 'Credit'], key=str.lower,reverse = True)
# print(l)

# def is_odd(n):
#     return n % 2 == 1
# l = list(filter(is_odd, [1, 2, 4, 5, 6, 9, 10, 15]))
# print(l)

# l =  list(map(str, [1, 2, 3, 4, 5, 6, 7, 8, 9]))
# print(l)
# def add(x,y):
#   return x+y
# r = reduce(add,l)
# print(r)

# def triangel(n):
#     L=[1]                                                                 #定义一个list[1]
#     while True:
#         #yield L                                                           #打印出该list
#         print(L)
#         L=[L[x]+L[x+1] for x in range(len(L)-1)]        #计算下一行中间的值(除去两边的1)
#         L.insert(0,1)                                                 #在开头插入1
#         L.append(1)                                                 #在结尾添加1
#         if len(L)>10:                                                 #仅输出10行
#             break
# triangel(10)

# def fib(max):
#   n,a,b =0,0,1
#   while n=0:
#       return x
#   else:
#       return -x
# print(my_abs('ab'))

# s = set([1,2,3])
# print(s)

# names = {'stu1':54,'stu2':34}
# #print(names['stu'])
# print(names.get('stu',-1))

# sum =0
# n = 99
# while n>0:
#   sum = sum+n
#   n = n-2
#   if n <10:
#       break;
# print(sum)

# sum = 0
# for x in range(101):
#   sum = sum+x
# print(sum)

# a =6
# if a>=10:
#   print('bigger than 10')
# elif a>=5:
#   print('bigger than 5')
# else:
#   print('else ...')

# mates = ['a','b','c']
# mates.append('d')
# print(mates)

#print('%2d-%02d' % (123,1))

#print(b'ABC'.decode('ascii'))

#print(chr(66))

#print(ord('中'))

# print(0.3//3)

# x= 10
# x =x+2
# print(x)

# print(r'a\nb','c\nd')

# print('''line1
# line
# line3''')

#print("this is test")

#print(r'\\t\\')

你可能感兴趣的:(Python初探及入门)