1. hello world
#!/usr/bin/env python3#-*- coding: utf-8 -*-__authon__ = '275120399@qq.com'if __name__ == '__main__': print("hello word!") print("你好,Python!")
2. 读文件 and 写文件
#!/usr/bin/env python3#-*- coding: utf-8 -*-# 读一个文件fp = open("./test.txt", "r");content = fp.read();print(content)fp.close();# 写一个文件fp1 = open("./text2.txt", "w");fp1.write(content)fp1.close()# 追加写入一个文件,用w会是覆盖写fp1 = open("./text2.txt", "a");fp1.write(content)fp1.close()# 关键词 with 不再需要访问文件后进行关闭,会自动进行关闭。 with open("./dog.txt", 'r') as file_obj: print(file_obj.read())
3. 按行读文件
#!/usr/bin/env python3#-*- coding: utf-8 -*-fp1 = open("./test.txt", "r");# 按行读一个文件list = fp1.readlines()for l in list: print(l)fp1.close()
4. 将json写入文件
#!/usr/bin/env python3#-*- coding: utf-8 -*-import jsonusers = [{ 'name': '小王', 'score': 95},{ 'name': '小黑', 'score': 88}]# [{"name": "\u5c0f\u738b", "score": 95}, {"name": "\u5c0f\u9ed1", "score": 88}]with open('a.JSON', 'w') as fp: json.dump(users, fp)
5. 读json文件
#!/usr/bin/env python3#-*- coding: utf-8 -*-import jsonwith open('a.JSON', 'r', encoding='utf-8') as fp: json_str=json.load(fp) print(json_str)
6. json to string
#!/usr/bin/env python3#-*- coding: utf-8 -*-import jsonusers = [{ 'name': '小王', 'score': 95},{ 'name': '小黑', 'score': 88}]json_str = json.dumps(users, ensure_ascii=False)print(json_str)
7. string to json
#!/usr/bin/env python3#-*- coding: utf-8 -*-import jsonusers_str = '[{"name": "小王", "score": 95},{"name": "小黑","score": 88}]'users = json.loads(users_str, encoding='utf-8')print(type(users))print(users)
8. 打开一个sqlite3
#!/usr/bin/env python3#-*- coding utf-8 -*-import sqlite3 as sqlcon = sql.connect("my_db.db")if con: print("成功连接数据库") con.close()
9. string 去掉头尾空格
#!/usr/bin/env python3#-*- coding utf-8 -*-str = " hello python3 world! "a = 'a'b = 'b'c = 'c'# + 字符串连接,还可以使用 \n\t 换行符,制表符d = a + '-' + b + '-' + cprint(d)# 去掉末尾空格print(str.rstrip())# 去掉头部空格print(str.lstrip() + 'end')# 去掉头末尾空格print(str.strip() + 'end')
10. 数值类型转换字符串类型
#!/usr/bin/env python3#-*- coding utf-8 -*-print(1 + 2)print(2 - 1)print(10 / 5)print(2 * 5)# 乘方 2的四次方print(2 ** 4)# 浮点数 注意0.30000000000000004print(0.2 + 0.1)# 数值转字符串print(str(0.2 + 0.1))# 注意整数和浮点数的除法print(3 / 2) # 注意 python2的话这个结果会是1print(3.0 / 2) # 这个结果是1.5
11. 数组(列表)操作
#!/usr/bin/env python3#-*- coding utf-8 -*-arr = ['a', 'b', 'c']print(arr[0])# -1 是最后一个元素,从后往前print(arr[-1])# 追加arr.append('d')# 修改arr[0] = '1'print(arr) # ['1', 'b', 'c', 'd']# 插入arr.insert(0, '2')print(arr) # ['2', '1', 'b', 'c', 'd']del arr[0]print(arr) # ['1', 'b', 'c', 'd']# 提取出数组最后一个值,并在数组中将他删除temp = arr.pop()print(temp) # 'd'print(arr) # ['1', 'b', 'c']# 还可以指定从那个位置提取并删除temp = arr.pop(1) # 'b'print(temp)print(arr) # ['1', 'c']arr = ['a' ,'b', 'c', 'c']# 删除指定的值,需要注意,它只删除第一个指定的值arr.remove('c')print(arr) # ['a', 'b', 'c']# 排序arr.sort(reverse=True)print(arr) # ['c', 'b', 'a']arr.sort()print(arr) # ['a', 'b', 'c']# 临时排序print(sorted(arr, reverse=True))print(arr) # ['a', 'b', 'c']# 反转顺序arr.reverse()print(arr) # ['c', 'b', 'a']# 数组长度print(len(arr)) # 3
12. 数组切片
#!/usr/bin/env python3#-*- coding utf-8 -*-arr = ['a', 'b', 'c']for temp in arr: print(temp)# 创建数值列表 输出从1到4,不包含5for temp in range(1, 5): print(temp)# 创建一个列表, range设置步长为2arr = list(range(1, 11, 2)) # [1, 3, 5, 7, 9]print(arr)print(max(arr))print(min(arr))print(sum(arr))# 列表解析squares = [value ** 2 for value in range(1, 11)]print(squares)# 列表切片arr = ['a', 'b', 'c', 'd', 'e']print(arr[1:3]) # 输出 1到3 不包含3 ['b', 'c']print(arr[1:]) # 输出 1到最后 ['b', 'c', 'd', 'e']print(arr[-3:]) # ['c', 'd', 'e']print([value for value in arr[:3]]) # 输出前3名# copy 数组arrCopy = arr[:]print(arrCopy) # ['a', 'b', 'c', 'd', 'e']
13. 元组
#!/usr/bin/env python3#-*- coding utf-8 -*-# 元组,不能修改,dimensions = (200, 50)print(dimensions)print(dimensions[0])print(dimensions[1])# dimensions[0] = 250 # 这样写会抛出错误for dimension in dimensions: print(dimension)# 虽然元组值不能修改,但是元组的那个变量可以重新赋值dimensions = (100, 300)print(dimensions)
14. if elif else
#!/usr/bin/env python3#-*- coding utf-8 -*-cars = ['aUDI', 'bmw', 'subaru', 'toyota']for car in cars: if car == 'aUDI': print(car.upper()) # 全大写 print(car.lower()) # 全小写 else: print(car.title()) # 首字母大写num = 19if num <= 20 and num >= 10: print(str(num) + ' <= 20 and ' + str(num) + ' >= 10')if num == 18 or num == 19: print(str(num) + ' == 18 or ' + str(num) + ' == 19 ')arr = ['a', 'b', 'c']# in 的使用,包含if 'a' in arr: print('a in ' + str(arr))arr = ['a', 'b', 'c']# not in 的使用,包含if ('a' not in arr) == False: print('a not in ' + str(arr))if num == 8: print('8')elif num == 9: print('9')else: print(num)arr = []if arr: # 空数组默认是Flase print('arr is not empty')else: print('arr is empty')
15.字典
#!/usr/bin/env python3#-*- coding utf-8 -*-alien_0 = { 'color': 'green', 'points': 5}print(alien_0['color']) # greenprint(alien_0['points']) # 5# 赋值或修改值alien_0['x-position'] = 'x'alien_0['y-position'] = 'y'print(alien_0) # {'color': 'green', 'points': 5, 'x-position': 'x', 'y-position': 'y'}# 删除一个值del alien_0['color']print(alien_0) # {'points': 5, 'x-position': 'x', 'y-position': 'y'}# 遍历 key,valuefor key, value in alien_0.items(): print(str(key) + ' ' + str(value))# 遍历 keyfor key in alien_0.keys(): print(str(key))# 遍历 valuefor value in alien_0.values(): print(str(value))
16. 循环和接收输入
#!/usr/bin/env python3#-*- coding utf-8 -*-prompt = "If you tell us who you are, we can personalize the message you see."prompt += "\nWhat is your first name?"# 接收用户输入name = input(prompt) print('hello ' + name)age = input('How old are you?')age = int(age)# 获取用户输入数值print('age ' + str(age))# 求模运算print(4 % 3)print(4 % 2)print('---')current_number = 1while current_number <= 10: current_number += 1 if current_number % 2: continue # 退出当前循环 print(current_number) if current_number == 8: break # 退出循环
17. def 函数
#!/usr/bin/env python3#-*- coding utf-8 -*-def greet_user(username): # 形参,实参 """显示简单的问候语""" print("hello " + username)greet_user("lijunyang")def hello_user(username, message): print(message + username)# 指定命名参数hello_user(message="hello ", username="lijunyang")# 设置默认参数def hello_user_0(username="lijunyang", message="hello "): print(message + username) # 返回内容 return "abc"print(hello_user_0())def hello_user_1(arr): print(arr)arr = ['a', 'b', 'c']# 传递函数副本,这样它就不会被改变值了hello_user_1(arr[:])# 传递任意数量的参数def hello_user_2(temp, *temps): print(temp) print(temps)hello_user_2("d", "e", "f") # 会传递一个元组进去def hello_user_3(temp, **temps): print(temp) for key, value in temps.items(): print(key +":"+ value)hello_user_3("q", a="w", b="e", c="r")
18. import 函数
# index.py#!/usr/bin/env python3#-*- coding utf-8 -*-# 指定模块import hellohello.greet_user('lijunyang')# 指定模块import hello as pp.greet_user('666')# 指定引入那个函数from hello import greet_user_0greet_user_0()# 指定引入那个函数并取别名from hello import greet_user_0 as fnfn()# hello.py#!/usr/bin/env python3#-*- coding utf-8 -*-def greet_user(username): # 形参,实参 """显示简单的问候语""" print("hello " + username)def greet_user_0(username = 'zhangchao'): # 形参,实参 """显示简单的问候语""" print("hello " + username)# test.py# 导出模块中所有函数from hello import *greet_user_0()
19. class import
# dog.py#!/usr/bin/env python3#-*- coding utf-8 -*-class Dog(): # 实例化方法 def __init__(self, name, age): """初始化属性name和age""" self.name = name self.age = age def sit(self): """模拟小狗蹲下""" print(self.name.title() + " is now sitting.") def roll_over(self): """模拟小狗打滚""" print(self.name.title() + " rolled over!") def get_age(self): """获取小狗年龄""" print("The dog's age is " + str(self.age)) def set_age(self, age): self.age = ageclass Log(): def __init__(self): self.name = "log" def log(self): print(self.name.title())# 继承class BigDog(Dog): def __init__(self, name, age, height): super().__init__(name, age) self.height = height self.log = Log() # 使用实例作为属性 def get_age(self): # 重写方法 """获取小狗年龄""" print("The " + self.name + "'s age is " + str(self.age)) def get_height(self): """获取小狗的高度""" print("The dog`s height is " + str(self.height))# index.py#!/usr/bin/env python3#-*- coding utf-8 -*-# 导入整个模块import dog# 在一个文件中导入多个classfrom dog import Dog, BigDog# from dog import * # 导出此模块所有classmy_dog = dog.Dog("xiaogou", 2)my_dog.sit()my_dog.roll_over()my_dog.get_age() # 2my_dog.age = 6 # 可以直接通过属性修改年龄my_dog.get_age() # 6my_dog.set_age(10)my_dog.get_age() # 10big_dog = BigDog("bigdog", 2, "20cm")big_dog.sit()big_dog.roll_over()big_dog.get_age() # 2big_dog.get_height() # 20cmbig_dog.log.log() # log
20. 字典类和随机
#!/usr/bin/env python3#-*- coding utf-8 -*-from random import randintfrom collections import OrderedDictx = randint(1, 6) # 随机出一个数字,范围是1到6print(str(x))obj = OrderedDict()obj['a'] = '1'obj['b'] = '2'for key,value in obj.items(): print(key + " " + value)
21. try … except
#!/usr/bin/env python3#-*- coding utf-8 -*-try: answer = 5 / 1except ZeroDivisionError: print("You can`t divide by zero!")else: # try: 内语句执行正确时,执行 else 代码块 print(answer)try: answer = 5 / 0except ZeroDivisionError: # 希望失败时什么也不做 passelse: # try: 内语句执行正确时,执行 else 代码块 print(answer)# FileNotFoundError
22. 读写json
#!/usr/bin/env python3#-*- coding utf-8 -*-# 不仅可以存储json格式的,也可以直接存储string的内容import jsonusername = input("What is your name? ")filename = './test/username.json'with open(filename, 'w') as file_obj: json.dump(username, file_obj) print("We`ll remember you when you come back, " + username + " !")with open(filename, 'r') as file_obj: username = json.load(file_obj) print("Welcome back, " + username)
23. 查询帮助文档
#!/usr/bin/env python3#-*- coding utf-8 -*-from lxml import etreehelp(etree)
24. 线程与线程同步
#!/usr/bin/python3# -*- coding: UTF-8 -*-import threadingimport time# 为线程定义一个函数def print_time(threadName, delay): count = 0 while count < 5: # 利用time.sleep切换线程 time.sleep(delay) count += 1 print("%s: %s" % (threadName, time.ctime(time.time())))# 创建两个线程try: t = threading.Thread(target=print_time, args=("Thread-1", 0.01, )) t1 = threading.Thread(target=print_time, args=("Thread-2", 0.01, )) t.start() t1.start()except: print("Error: unable to start thread")while 1: pass
#!/usr/bin/python3# -*- coding: UTF-8 -*-import threadingimport time# run(): 用以表示线程活动的方法。# start(): 启动线程活动。# join([time]): 等待至线程中止。这阻塞调用线程直至线程的join() 方法被调用中止-正常退出或者抛出未处理的异常-或者是可选的超时发生。# isAlive(): 返回线程是否活动的。# getName(): 返回线程名。# setName(): 设置线程名。class myThread (threading.Thread): def __init__(self, threadID, name, counter): threading.Thread.__init__(self) self.threadID = threadID self.name = name self.counter = counter def run(self): print("Starting " + self.name) # 获得锁,成功获得锁定后返回True # 可选的timeout参数不填时将一直阻塞直到获得锁定 # 否则超时后将返回False threadLock.acquire() print_time(self.name, self.counter, 3) # 释放锁 threadLock.release()def print_time(threadName, delay, counter): while counter: time.sleep(delay) print("%s: %s" % (threadName, time.ctime(time.time()))) counter -= 1threadLock = threading.Lock()threads = []# 创建新线程thread1 = myThread(1, "Thread-1", 1)thread2 = myThread(2, "Thread-2", 1)# 开启新线程thread1.start()thread2.start()# 添加线程到线程列表threads.append(thread1)threads.append(thread2)# 等待所有线程完成for t in threads: t.join()print("Exiting Main Thread")
25. Queue 队列 and 栈 的使用
#!/usr/bin/python3# -*- coding: UTF-8 -*-import queueimport threadingimport time# help(queue.Queue)# queue.LifoQueue 栈 ,先进后出# 创建一个队列,队列长度最大为10_queue = queue.Queue(10)# 返回队列最大长度print(_queue.maxsize) # 10list = [1,2,3,4,5,6,7,8,9,10]for value in list: # 写入队列 _queue.put(value)# 返回队列是否为空print(_queue.empty()) # Flash# 返回队列是否是满的print(_queue.full()) # True# 返回队列数量print(_queue.qsize()) # 10# 出队列v = _queue.get()print(v) # 1# 返回队列数量print(_queue.qsize()) # 9v = _queue.get(block=False, timeout=1)print(v) # 2v = _queue.get(block=True, timeout=1)print(v) # 3
timeout 的使用
#!/usr/bin/python3# -*- coding: UTF-8 -*-import queueimport timeimport threadingdef print_time(threadName, delay): count = 0 while count < 5: # 利用time.sleep切换线程 time.sleep(delay) count += 1 print("%s: %s" % (threadName, time.ctime(time.time()))) if count == 1: print('%s: %s' % (threadName, q.get())) if count == 4: q.put('B')t = threading.Thread(target=print_time, args=("Thread-1", 1))t.start()q = queue.Queue(10)for i in range(11): myData = 'A' # block=False timeout会失效 # block=True,并且设定了timeout时,当队列清空后,再次put会等待timeout秒 # ,如果在等待过程中有内容取出则继续执行,否则抛出异常 raise Full q.put(myData, block=True, timeout=10) # time.sleep(0.2)for i in range(11): # block=False timeout会失效 # block=True,并且设定了timeout时,当队列清空后,再次get会等待timeout秒 # ,如果在等待过程中有内容插入则继续执行,否则抛出异常 raise Empty print(q.get(block=True, timeout=10))