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 json
users = [
{
'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 json
with 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 json
users = [
{
'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 json
users_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 sql
con = 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 + '-' + c
print(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.30000000000000004
print(0.2 + 0.1)
# 数值转字符串
print(str(0.2 + 0.1))
# 注意整数和浮点数的除法
print(3 / 2) # 注意 python2的话这个结果会是1
print(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,不包含5
for temp in range(1, 5):
print(temp)
# 创建一个列表, range设置步长为2
arr = 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 = 19
if 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']) # green
print(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,value
for key, value in alien_0.items():
print(str(key) + ' ' + str(value))
# 遍历 key
for key in alien_0.keys():
print(str(key))
# 遍历 value
for 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 = 1
while 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 hello
hello.greet_user('lijunyang')
# 指定模块
import hello as p
p.greet_user('666')
# 指定引入那个函数
from hello import greet_user_0
greet_user_0()
# 指定引入那个函数并取别名
from hello import greet_user_0 as fn
fn()
# 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 = age
class 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
# 在一个文件中导入多个class
from dog import Dog, BigDog
# from dog import * # 导出此模块所有class
my_dog = dog.Dog("xiaogou", 2)
my_dog.sit()
my_dog.roll_over()
my_dog.get_age() # 2
my_dog.age = 6 # 可以直接通过属性修改年龄
my_dog.get_age() # 6
my_dog.set_age(10)
my_dog.get_age() # 10
big_dog = BigDog("bigdog", 2, "20cm")
big_dog.sit()
big_dog.roll_over()
big_dog.get_age() # 2
big_dog.get_height() # 20cm
big_dog.log.log() # log
20. 字典类和随机
#!/usr/bin/env python3
#-*- coding utf-8 -*-
from random import randint
from collections import OrderedDict
x = randint(1, 6) # 随机出一个数字,范围是1到6
print(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 / 1
except ZeroDivisionError:
print("You can`t divide by zero!")
else: # try: 内语句执行正确时,执行 else 代码块
print(answer)
try:
answer = 5 / 0
except ZeroDivisionError:
# 希望失败时什么也不做
pass
else: # try: 内语句执行正确时,执行 else 代码块
print(answer)
# FileNotFoundError
22. 读写json
#!/usr/bin/env python3
#-*- coding utf-8 -*-
# 不仅可以存储json格式的,也可以直接存储string的内容
import json
username = 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 etree
help(etree)
24. 线程与线程同步
#!/usr/bin/python3
# -*- coding: UTF-8 -*-
import threading
import 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 threading
import 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 -= 1
threadLock = 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 queue
import threading
import time
# help(queue.Queue)
# queue.LifoQueue 栈 ,先进后出
# 创建一个队列,队列长度最大为10
_queue = queue.Queue(10)
# 返回队列最大长度
print(_queue.maxsize) # 10
list = [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()) # 9
v = _queue.get(block=False, timeout=1)
print(v) # 2
v = _queue.get(block=True, timeout=1)
print(v) # 3
timeout 的使用
#!/usr/bin/python3
# -*- coding: UTF-8 -*-
import queue
import time
import threading
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())))
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))