1. hello world

  1. #!/usr/bin/env python3
  2. #-*- coding: utf-8 -*-
  3. __authon__ = '275120399@qq.com'
  4. if __name__ == '__main__':
  5. print("hello word!")
  6. print("你好,Python!")

2. 读文件 and 写文件

  1. #!/usr/bin/env python3
  2. #-*- coding: utf-8 -*-
  3. # 读一个文件
  4. fp = open("./test.txt", "r");
  5. content = fp.read();
  6. print(content)
  7. fp.close();
  8. # 写一个文件
  9. fp1 = open("./text2.txt", "w");
  10. fp1.write(content)
  11. fp1.close()
  12. # 追加写入一个文件,用w会是覆盖写
  13. fp1 = open("./text2.txt", "a");
  14. fp1.write(content)
  15. fp1.close()
  16. # 关键词 with 不再需要访问文件后进行关闭,会自动进行关闭。
  17. with open("./dog.txt", 'r') as file_obj:
  18. print(file_obj.read())

3. 按行读文件

  1. #!/usr/bin/env python3
  2. #-*- coding: utf-8 -*-
  3. fp1 = open("./test.txt", "r");
  4. # 按行读一个文件
  5. list = fp1.readlines()
  6. for l in list:
  7. print(l)
  8. fp1.close()

4. 将json写入文件

  1. #!/usr/bin/env python3
  2. #-*- coding: utf-8 -*-
  3. import json
  4. users = [
  5. {
  6. 'name': '小王',
  7. 'score': 95
  8. },
  9. {
  10. 'name': '小黑',
  11. 'score': 88
  12. }
  13. ]
  14. # [{"name": "\u5c0f\u738b", "score": 95}, {"name": "\u5c0f\u9ed1", "score": 88}]
  15. with open('a.JSON', 'w') as fp:
  16. json.dump(users, fp)

5. 读json文件

  1. #!/usr/bin/env python3
  2. #-*- coding: utf-8 -*-
  3. import json
  4. with open('a.JSON', 'r', encoding='utf-8') as fp:
  5. json_str=json.load(fp)
  6. print(json_str)

6. json to string

  1. #!/usr/bin/env python3
  2. #-*- coding: utf-8 -*-
  3. import json
  4. users = [
  5. {
  6. 'name': '小王',
  7. 'score': 95
  8. },
  9. {
  10. 'name': '小黑',
  11. 'score': 88
  12. }
  13. ]
  14. json_str = json.dumps(users, ensure_ascii=False)
  15. print(json_str)

7. string to json

  1. #!/usr/bin/env python3
  2. #-*- coding: utf-8 -*-
  3. import json
  4. users_str = '[{"name": "小王", "score": 95},{"name": "小黑","score": 88}]'
  5. users = json.loads(users_str, encoding='utf-8')
  6. print(type(users))
  7. print(users)

8. 打开一个sqlite3

  1. #!/usr/bin/env python3
  2. #-*- coding utf-8 -*-
  3. import sqlite3 as sql
  4. con = sql.connect("my_db.db")
  5. if con:
  6. print("成功连接数据库")
  7. con.close()

9. string 去掉头尾空格

  1. #!/usr/bin/env python3
  2. #-*- coding utf-8 -*-
  3. str = " hello python3 world! "
  4. a = 'a'
  5. b = 'b'
  6. c = 'c'
  7. # + 字符串连接,还可以使用 \n\t 换行符,制表符
  8. d = a + '-' + b + '-' + c
  9. print(d)
  10. # 去掉末尾空格
  11. print(str.rstrip())
  12. # 去掉头部空格
  13. print(str.lstrip() + 'end')
  14. # 去掉头末尾空格
  15. print(str.strip() + 'end')

10. 数值类型转换字符串类型

  1. #!/usr/bin/env python3
  2. #-*- coding utf-8 -*-
  3. print(1 + 2)
  4. print(2 - 1)
  5. print(10 / 5)
  6. print(2 * 5)
  7. # 乘方 2的四次方
  8. print(2 ** 4)
  9. # 浮点数 注意0.30000000000000004
  10. print(0.2 + 0.1)
  11. # 数值转字符串
  12. print(str(0.2 + 0.1))
  13. # 注意整数和浮点数的除法
  14. print(3 / 2) # 注意 python2的话这个结果会是1
  15. print(3.0 / 2) # 这个结果是1.5

11. 数组(列表)操作

  1. #!/usr/bin/env python3
  2. #-*- coding utf-8 -*-
  3. arr = ['a', 'b', 'c']
  4. print(arr[0])
  5. # -1 是最后一个元素,从后往前
  6. print(arr[-1])
  7. # 追加
  8. arr.append('d')
  9. # 修改
  10. arr[0] = '1'
  11. print(arr) # ['1', 'b', 'c', 'd']
  12. # 插入
  13. arr.insert(0, '2')
  14. print(arr) # ['2', '1', 'b', 'c', 'd']
  15. del arr[0]
  16. print(arr) # ['1', 'b', 'c', 'd']
  17. # 提取出数组最后一个值,并在数组中将他删除
  18. temp = arr.pop()
  19. print(temp) # 'd'
  20. print(arr) # ['1', 'b', 'c']
  21. # 还可以指定从那个位置提取并删除
  22. temp = arr.pop(1) # 'b'
  23. print(temp)
  24. print(arr) # ['1', 'c']
  25. arr = ['a' ,'b', 'c', 'c']
  26. # 删除指定的值,需要注意,它只删除第一个指定的值
  27. arr.remove('c')
  28. print(arr) # ['a', 'b', 'c']
  29. # 排序
  30. arr.sort(reverse=True)
  31. print(arr) # ['c', 'b', 'a']
  32. arr.sort()
  33. print(arr) # ['a', 'b', 'c']
  34. # 临时排序
  35. print(sorted(arr, reverse=True))
  36. print(arr) # ['a', 'b', 'c']
  37. # 反转顺序
  38. arr.reverse()
  39. print(arr) # ['c', 'b', 'a']
  40. # 数组长度
  41. print(len(arr)) # 3

12. 数组切片

  1. #!/usr/bin/env python3
  2. #-*- coding utf-8 -*-
  3. arr = ['a', 'b', 'c']
  4. for temp in arr:
  5. print(temp)
  6. # 创建数值列表 输出从1到4,不包含5
  7. for temp in range(1, 5):
  8. print(temp)
  9. # 创建一个列表, range设置步长为2
  10. arr = list(range(1, 11, 2)) # [1, 3, 5, 7, 9]
  11. print(arr)
  12. print(max(arr))
  13. print(min(arr))
  14. print(sum(arr))
  15. # 列表解析
  16. squares = [value ** 2 for value in range(1, 11)]
  17. print(squares)
  18. # 列表切片
  19. arr = ['a', 'b', 'c', 'd', 'e']
  20. print(arr[1:3]) # 输出 1到3 不包含3 ['b', 'c']
  21. print(arr[1:]) # 输出 1到最后 ['b', 'c', 'd', 'e']
  22. print(arr[-3:]) # ['c', 'd', 'e']
  23. print([value for value in arr[:3]]) # 输出前3名
  24. # copy 数组
  25. arrCopy = arr[:]
  26. print(arrCopy) # ['a', 'b', 'c', 'd', 'e']

13. 元组

  1. #!/usr/bin/env python3
  2. #-*- coding utf-8 -*-
  3. # 元组,不能修改,
  4. dimensions = (200, 50)
  5. print(dimensions)
  6. print(dimensions[0])
  7. print(dimensions[1])
  8. # dimensions[0] = 250 # 这样写会抛出错误
  9. for dimension in dimensions:
  10. print(dimension)
  11. # 虽然元组值不能修改,但是元组的那个变量可以重新赋值
  12. dimensions = (100, 300)
  13. print(dimensions)

14. if elif else

  1. #!/usr/bin/env python3
  2. #-*- coding utf-8 -*-
  3. cars = ['aUDI', 'bmw', 'subaru', 'toyota']
  4. for car in cars:
  5. if car == 'aUDI':
  6. print(car.upper()) # 全大写
  7. print(car.lower()) # 全小写
  8. else:
  9. print(car.title()) # 首字母大写
  10. num = 19
  11. if num <= 20 and num >= 10:
  12. print(str(num) + ' <= 20 and ' + str(num) + ' >= 10')
  13. if num == 18 or num == 19:
  14. print(str(num) + ' == 18 or ' + str(num) + ' == 19 ')
  15. arr = ['a', 'b', 'c']
  16. # in 的使用,包含
  17. if 'a' in arr:
  18. print('a in ' + str(arr))
  19. arr = ['a', 'b', 'c']
  20. # not in 的使用,包含
  21. if ('a' not in arr) == False:
  22. print('a not in ' + str(arr))
  23. if num == 8:
  24. print('8')
  25. elif num == 9:
  26. print('9')
  27. else:
  28. print(num)
  29. arr = []
  30. if arr: # 空数组默认是Flase
  31. print('arr is not empty')
  32. else:
  33. print('arr is empty')

15.字典

  1. #!/usr/bin/env python3
  2. #-*- coding utf-8 -*-
  3. alien_0 = {
  4. 'color': 'green',
  5. 'points': 5
  6. }
  7. print(alien_0['color']) # green
  8. print(alien_0['points']) # 5
  9. # 赋值或修改值
  10. alien_0['x-position'] = 'x'
  11. alien_0['y-position'] = 'y'
  12. print(alien_0) # {'color': 'green', 'points': 5, 'x-position': 'x', 'y-position': 'y'}
  13. # 删除一个值
  14. del alien_0['color']
  15. print(alien_0) # {'points': 5, 'x-position': 'x', 'y-position': 'y'}
  16. # 遍历 key,value
  17. for key, value in alien_0.items():
  18. print(str(key) + ' ' + str(value))
  19. # 遍历 key
  20. for key in alien_0.keys():
  21. print(str(key))
  22. # 遍历 value
  23. for value in alien_0.values():
  24. print(str(value))

16. 循环和接收输入

  1. #!/usr/bin/env python3
  2. #-*- coding utf-8 -*-
  3. prompt = "If you tell us who you are, we can personalize the message you see."
  4. prompt += "\nWhat is your first name?"
  5. # 接收用户输入
  6. name = input(prompt)
  7. print('hello ' + name)
  8. age = input('How old are you?')
  9. age = int(age)
  10. # 获取用户输入数值
  11. print('age ' + str(age))
  12. # 求模运算
  13. print(4 % 3)
  14. print(4 % 2)
  15. print('---')
  16. current_number = 1
  17. while current_number <= 10:
  18. current_number += 1
  19. if current_number % 2:
  20. continue # 退出当前循环
  21. print(current_number)
  22. if current_number == 8:
  23. break # 退出循环

17. def 函数

  1. #!/usr/bin/env python3
  2. #-*- coding utf-8 -*-
  3. def greet_user(username): # 形参,实参
  4. """显示简单的问候语"""
  5. print("hello " + username)
  6. greet_user("lijunyang")
  7. def hello_user(username, message):
  8. print(message + username)
  9. # 指定命名参数
  10. hello_user(message="hello ", username="lijunyang")
  11. # 设置默认参数
  12. def hello_user_0(username="lijunyang", message="hello "):
  13. print(message + username)
  14. # 返回内容
  15. return "abc"
  16. print(hello_user_0())
  17. def hello_user_1(arr):
  18. print(arr)
  19. arr = ['a', 'b', 'c']
  20. # 传递函数副本,这样它就不会被改变值了
  21. hello_user_1(arr[:])
  22. # 传递任意数量的参数
  23. def hello_user_2(temp, *temps):
  24. print(temp)
  25. print(temps)
  26. hello_user_2("d", "e", "f") # 会传递一个元组进去
  27. def hello_user_3(temp, **temps):
  28. print(temp)
  29. for key, value in temps.items():
  30. print(key +":"+ value)
  31. hello_user_3("q", a="w", b="e", c="r")

18. import 函数

  1. # index.py
  2. #!/usr/bin/env python3
  3. #-*- coding utf-8 -*-
  4. # 指定模块
  5. import hello
  6. hello.greet_user('lijunyang')
  7. # 指定模块
  8. import hello as p
  9. p.greet_user('666')
  10. # 指定引入那个函数
  11. from hello import greet_user_0
  12. greet_user_0()
  13. # 指定引入那个函数并取别名
  14. from hello import greet_user_0 as fn
  15. fn()
  16. # hello.py
  17. #!/usr/bin/env python3
  18. #-*- coding utf-8 -*-
  19. def greet_user(username): # 形参,实参
  20. """显示简单的问候语"""
  21. print("hello " + username)
  22. def greet_user_0(username = 'zhangchao'): # 形参,实参
  23. """显示简单的问候语"""
  24. print("hello " + username)
  25. # test.py
  26. # 导出模块中所有函数
  27. from hello import *
  28. greet_user_0()

19. class import

  1. # dog.py
  2. #!/usr/bin/env python3
  3. #-*- coding utf-8 -*-
  4. class Dog():
  5. # 实例化方法
  6. def __init__(self, name, age):
  7. """初始化属性name和age"""
  8. self.name = name
  9. self.age = age
  10. def sit(self):
  11. """模拟小狗蹲下"""
  12. print(self.name.title() + " is now sitting.")
  13. def roll_over(self):
  14. """模拟小狗打滚"""
  15. print(self.name.title() + " rolled over!")
  16. def get_age(self):
  17. """获取小狗年龄"""
  18. print("The dog's age is " + str(self.age))
  19. def set_age(self, age):
  20. self.age = age
  21. class Log():
  22. def __init__(self):
  23. self.name = "log"
  24. def log(self):
  25. print(self.name.title())
  26. # 继承
  27. class BigDog(Dog):
  28. def __init__(self, name, age, height):
  29. super().__init__(name, age)
  30. self.height = height
  31. self.log = Log() # 使用实例作为属性
  32. def get_age(self): # 重写方法
  33. """获取小狗年龄"""
  34. print("The " + self.name + "'s age is " + str(self.age))
  35. def get_height(self):
  36. """获取小狗的高度"""
  37. print("The dog`s height is " + str(self.height))
  38. # index.py
  39. #!/usr/bin/env python3
  40. #-*- coding utf-8 -*-
  41. # 导入整个模块
  42. import dog
  43. # 在一个文件中导入多个class
  44. from dog import Dog, BigDog
  45. # from dog import * # 导出此模块所有class
  46. my_dog = dog.Dog("xiaogou", 2)
  47. my_dog.sit()
  48. my_dog.roll_over()
  49. my_dog.get_age() # 2
  50. my_dog.age = 6 # 可以直接通过属性修改年龄
  51. my_dog.get_age() # 6
  52. my_dog.set_age(10)
  53. my_dog.get_age() # 10
  54. big_dog = BigDog("bigdog", 2, "20cm")
  55. big_dog.sit()
  56. big_dog.roll_over()
  57. big_dog.get_age() # 2
  58. big_dog.get_height() # 20cm
  59. big_dog.log.log() # log

20. 字典类和随机

  1. #!/usr/bin/env python3
  2. #-*- coding utf-8 -*-
  3. from random import randint
  4. from collections import OrderedDict
  5. x = randint(1, 6) # 随机出一个数字,范围是1到6
  6. print(str(x))
  7. obj = OrderedDict()
  8. obj['a'] = '1'
  9. obj['b'] = '2'
  10. for key,value in obj.items():
  11. print(key + " " + value)

21. try … except

  1. #!/usr/bin/env python3
  2. #-*- coding utf-8 -*-
  3. try:
  4. answer = 5 / 1
  5. except ZeroDivisionError:
  6. print("You can`t divide by zero!")
  7. else: # try: 内语句执行正确时,执行 else 代码块
  8. print(answer)
  9. try:
  10. answer = 5 / 0
  11. except ZeroDivisionError:
  12. # 希望失败时什么也不做
  13. pass
  14. else: # try: 内语句执行正确时,执行 else 代码块
  15. print(answer)
  16. # FileNotFoundError

22. 读写json

  1. #!/usr/bin/env python3
  2. #-*- coding utf-8 -*-
  3. # 不仅可以存储json格式的,也可以直接存储string的内容
  4. import json
  5. username = input("What is your name? ")
  6. filename = './test/username.json'
  7. with open(filename, 'w') as file_obj:
  8. json.dump(username, file_obj)
  9. print("We`ll remember you when you come back, " + username + " !")
  10. with open(filename, 'r') as file_obj:
  11. username = json.load(file_obj)
  12. print("Welcome back, " + username)

23. 查询帮助文档

  1. #!/usr/bin/env python3
  2. #-*- coding utf-8 -*-
  3. from lxml import etree
  4. help(etree)

24. 线程与线程同步

  1. #!/usr/bin/python3
  2. # -*- coding: UTF-8 -*-
  3. import threading
  4. import time
  5. # 为线程定义一个函数
  6. def print_time(threadName, delay):
  7. count = 0
  8. while count < 5:
  9. # 利用time.sleep切换线程
  10. time.sleep(delay)
  11. count += 1
  12. print("%s: %s" % (threadName, time.ctime(time.time())))
  13. # 创建两个线程
  14. try:
  15. t = threading.Thread(target=print_time, args=("Thread-1", 0.01, ))
  16. t1 = threading.Thread(target=print_time, args=("Thread-2", 0.01, ))
  17. t.start()
  18. t1.start()
  19. except:
  20. print("Error: unable to start thread")
  21. while 1:
  22. pass
  1. #!/usr/bin/python3
  2. # -*- coding: UTF-8 -*-
  3. import threading
  4. import time
  5. # run(): 用以表示线程活动的方法。
  6. # start(): 启动线程活动。
  7. # join([time]): 等待至线程中止。这阻塞调用线程直至线程的join() 方法被调用中止-正常退出或者抛出未处理的异常-或者是可选的超时发生。
  8. # isAlive(): 返回线程是否活动的。
  9. # getName(): 返回线程名。
  10. # setName(): 设置线程名。
  11. class myThread (threading.Thread):
  12. def __init__(self, threadID, name, counter):
  13. threading.Thread.__init__(self)
  14. self.threadID = threadID
  15. self.name = name
  16. self.counter = counter
  17. def run(self):
  18. print("Starting " + self.name)
  19. # 获得锁,成功获得锁定后返回True
  20. # 可选的timeout参数不填时将一直阻塞直到获得锁定
  21. # 否则超时后将返回False
  22. threadLock.acquire()
  23. print_time(self.name, self.counter, 3)
  24. # 释放锁
  25. threadLock.release()
  26. def print_time(threadName, delay, counter):
  27. while counter:
  28. time.sleep(delay)
  29. print("%s: %s" % (threadName, time.ctime(time.time())))
  30. counter -= 1
  31. threadLock = threading.Lock()
  32. threads = []
  33. # 创建新线程
  34. thread1 = myThread(1, "Thread-1", 1)
  35. thread2 = myThread(2, "Thread-2", 1)
  36. # 开启新线程
  37. thread1.start()
  38. thread2.start()
  39. # 添加线程到线程列表
  40. threads.append(thread1)
  41. threads.append(thread2)
  42. # 等待所有线程完成
  43. for t in threads:
  44. t.join()
  45. print("Exiting Main Thread")

25. Queue 队列 and 栈 的使用

  1. #!/usr/bin/python3
  2. # -*- coding: UTF-8 -*-
  3. import queue
  4. import threading
  5. import time
  6. # help(queue.Queue)
  7. # queue.LifoQueue 栈 ,先进后出
  8. # 创建一个队列,队列长度最大为10
  9. _queue = queue.Queue(10)
  10. # 返回队列最大长度
  11. print(_queue.maxsize) # 10
  12. list = [1,2,3,4,5,6,7,8,9,10]
  13. for value in list:
  14. # 写入队列
  15. _queue.put(value)
  16. # 返回队列是否为空
  17. print(_queue.empty()) # Flash
  18. # 返回队列是否是满的
  19. print(_queue.full()) # True
  20. # 返回队列数量
  21. print(_queue.qsize()) # 10
  22. # 出队列
  23. v = _queue.get()
  24. print(v) # 1
  25. # 返回队列数量
  26. print(_queue.qsize()) # 9
  27. v = _queue.get(block=False, timeout=1)
  28. print(v) # 2
  29. v = _queue.get(block=True, timeout=1)
  30. print(v) # 3

timeout 的使用

  1. #!/usr/bin/python3
  2. # -*- coding: UTF-8 -*-
  3. import queue
  4. import time
  5. import threading
  6. def print_time(threadName, delay):
  7. count = 0
  8. while count < 5:
  9. # 利用time.sleep切换线程
  10. time.sleep(delay)
  11. count += 1
  12. print("%s: %s" % (threadName, time.ctime(time.time())))
  13. if count == 1:
  14. print('%s: %s' % (threadName, q.get()))
  15. if count == 4:
  16. q.put('B')
  17. t = threading.Thread(target=print_time, args=("Thread-1", 1))
  18. t.start()
  19. q = queue.Queue(10)
  20. for i in range(11):
  21. myData = 'A'
  22. # block=False timeout会失效
  23. # block=True,并且设定了timeout时,当队列清空后,再次put会等待timeout秒
  24. # ,如果在等待过程中有内容取出则继续执行,否则抛出异常 raise Full
  25. q.put(myData, block=True, timeout=10)
  26. # time.sleep(0.2)
  27. for i in range(11):
  28. # block=False timeout会失效
  29. # block=True,并且设定了timeout时,当队列清空后,再次get会等待timeout秒
  30. # ,如果在等待过程中有内容插入则继续执行,否则抛出异常 raise Empty
  31. print(q.get(block=True, timeout=10))