Commit 6411875f authored by jackfrued's avatar jackfrued

更正了部分文档和代码

parent 28067bfe
""" """
第一个Python程序 - hello, world! 第一个Python程序 - hello, world!
向伟大的Dennis M. Ritchie先生致敬 向伟大的Dennis M. Ritchie先生致敬
...@@ -9,7 +8,6 @@ Date: 2018-02-26 ...@@ -9,7 +8,6 @@ Date: 2018-02-26
请将该文件命名为hello.py并在终端中通过下面的命令运行它 请将该文件命名为hello.py并在终端中通过下面的命令运行它
python hello.py python hello.py
""" """
print('hello, world!') print('hello, world!')
......
""" """
将华氏温度转换为摄氏温度 将华氏温度转换为摄氏温度
F = 1.8C + 32 F = 1.8C + 32
Version: 0.1 Version: 0.1
Author: 骆昊 Author: 骆昊
Date: 2018-02-27 Date: 2018-02-27
""" """
f = float(input('请输入华氏温度: ')) f = float(input('请输入华氏温度: '))
......
""" """
输入半径计算圆的周长和面积 输入半径计算圆的周长和面积
Version: 0.1 Version: 0.1
Author: 骆昊 Author: 骆昊
Date: 2018-02-27 Date: 2018-02-27
""" """
import math import math
......
""" """
输入年份 如果是闰年输出True 否则输出False 输入年份 如果是闰年输出True 否则输出False
Version: 0.1 Version: 0.1
Author: 骆昊 Author: 骆昊
Date: 2018-02-27 Date: 2018-02-27
""" """
year = int(input('请输入年份: ')) year = int(input('请输入年份: '))
......
""" """
运算符的使用 运算符的使用
Version: 0.1 Version: 0.1
Author: 骆昊 Author: 骆昊
Date: 2018-02-27 Date: 2018-02-27
""" """
a = 5 a = 5
......
""" """
字符串常用操作 字符串常用操作
Version: 0.1 Version: 0.1
Author: 骆昊 Author: 骆昊
Date: 2018-02-27 Date: 2018-02-27
""" """
str1 = 'hello, world!' str1 = 'hello, world!'
......
""" """
使用变量保存数据并进行操作 使用变量保存数据并进行操作
Version: 0.1 Version: 0.1
Author: 骆昊 Author: 骆昊
Date: 2018-02-27 Date: 2018-02-27
""" """
a = 321 a = 321
......
""" """
将input函数输入的数据保存在变量中并进行操作 将input函数输入的数据保存在变量中并进行操作
Version: 0.1 Version: 0.1
Author: 骆昊 Author: 骆昊
Date: 2018-02-27 Date: 2018-02-27
""" """
a = int(input('a = ')) a = int(input('a = '))
......
""" """
格式化输出 格式化输出
Version: 0.1 Version: 0.1
Author: 骆昊 Author: 骆昊
Date: 2018-02-27 Date: 2018-02-27
""" """
a = int(input('a = ')) a = int(input('a = '))
......
""" """
检查变量的类型 检查变量的类型
Version: 0.1 Version: 0.1
Author: 骆昊 Author: 骆昊
Date: 2018-02-27 Date: 2018-02-27
""" """
a = 100 a = 100
......
""" """
类型转换 类型转换
Version: 0.1 Version: 0.1
Author: 骆昊 Author: 骆昊
Date: 2018-02-27 Date: 2018-02-27
""" """
a = 100 a = 100
......
""" """
英制单位英寸和公制单位厘米互换 英制单位英寸和公制单位厘米互换
Version: 0.1 Version: 0.1
Author: 骆昊 Author: 骆昊
Date: 2018-02-28 Date: 2018-02-28
""" """
value = float(input('请输入长度: ')) value = float(input('请输入长度: '))
unit = input('请输入单位: ') unit = input('请输入单位: ')
if unit == 'in' or unit == '英寸': if unit == 'in' or unit == '英寸':
print('%f英寸 = %f厘米' % (value, value * 2.54)) print('%f英寸 = %f厘米' % (value, value * 2.54))
elif unit == 'cm' or unit == '厘米': elif unit == 'cm' or unit == '厘米':
print('%f厘米 = %f英寸' % (value, value / 2.54)) print('%f厘米 = %f英寸' % (value, value / 2.54))
else: else:
print('请输入有效的单位') print('请输入有效的单位')
""" """
百分制成绩转等级制成绩 百分制成绩转等级制成绩
90分以上 --> A 90分以上 --> A
80分~89分 --> B 80分~89分 --> B
70分~79分 --> C 70分~79分 --> C
60分~69分 --> D 60分~69分 --> D
60分以下 --> E 60分以下 --> E
Version: 0.1 Version: 0.1
Author: 骆昊 Author: 骆昊
Date: 2018-02-28 Date: 2018-02-28
""" """
score = float(input('请输入成绩: ')) score = float(input('请输入成绩: '))
if score >= 90: if score >= 90:
grade = 'A' grade = 'A'
elif score >= 80: elif score >= 80:
grade = 'B' grade = 'B'
elif score >= 70: elif score >= 70:
grade = 'C' grade = 'C'
elif score >= 60: elif score >= 60:
grade = 'D' grade = 'D'
else: else:
grade = 'E' grade = 'E'
print('对应的等级是:', grade) print('对应的等级是:', grade)
""" """
分段函数求值 分段函数求值
3x - 5 (x > 1) 3x - 5 (x > 1)
f(x) = x + 2 (-1 <= x <= 1) f(x) = x + 2 (-1 <= x <= 1)
5x + 3 (x < -1) 5x + 3 (x < -1)
Version: 0.1 Version: 0.1
Author: 骆昊 Author: 骆昊
Date: 2018-02-28 Date: 2018-02-28
""" """
x = float(input('x = ')) x = float(input('x = '))
if x > 1: if x > 1:
y = 3 * x - 5 y = 3 * x - 5
elif x >= -1: elif x >= -1:
y = x + 2 y = x + 2
else: else:
y = 5 * x + 3 y = 5 * x + 3
print('f(%.2f) = %.2f' % (x, y)) print('f(%.2f) = %.2f' % (x, y))
""" """
掷骰子决定做什么事情 掷骰子决定做什么事情
Version: 0.1 Version: 0.1
Author: 骆昊 Author: 骆昊
Date: 2018-02-28 Date: 2018-02-28
""" """
from random import randint from random import randint
face = randint(1, 6) face = randint(1, 6)
if face == 1: if face == 1:
result = '唱首歌' result = '唱首歌'
elif face == 2: elif face == 2:
result = '跳个舞' result = '跳个舞'
elif face == 3: elif face == 3:
result = '学狗叫' result = '学狗叫'
elif face == 4: elif face == 4:
result = '做俯卧撑' result = '做俯卧撑'
elif face == 5: elif face == 5:
result = '念绕口令' result = '念绕口令'
else: else:
result = '讲冷笑话' result = '讲冷笑话'
print(result) print(result)
""" """
输入月收入和五险一金计算个人所得税 输入月收入和五险一金计算个人所得税
说明:写这段代码时新的个人所得税计算方式还没有颁布
Version: 0.1 Version: 0.1
Author: 骆昊 Author: 骆昊
Date: 2018-02-28 Date: 2018-02-28
""" """
salary = float(input('本月收入: ')) salary = float(input('本月收入: '))
insurance = float(input('五险一金: ')) insurance = float(input('五险一金: '))
diff = salary - insurance - 3500 diff = salary - insurance - 3500
if diff <= 0: if diff <= 0:
rate = 0 rate = 0
deduction = 0 deduction = 0
elif diff < 1500: elif diff < 1500:
rate = 0.03 rate = 0.03
deduction = 0 deduction = 0
elif diff < 4500: elif diff < 4500:
rate = 0.1 rate = 0.1
deduction = 105 deduction = 105
elif diff < 9000: elif diff < 9000:
rate = 0.2 rate = 0.2
deduction = 555 deduction = 555
elif diff < 35000: elif diff < 35000:
rate = 0.25 rate = 0.25
deduction = 1005 deduction = 1005
elif diff < 55000: elif diff < 55000:
rate = 0.3 rate = 0.3
deduction = 2755 deduction = 2755
elif diff < 80000: elif diff < 80000:
rate = 0.35 rate = 0.35
deduction = 5505 deduction = 5505
else: else:
rate = 0.45 rate = 0.45
deduction = 13505 deduction = 13505
tax = abs(diff * rate - deduction) tax = abs(diff * rate - deduction)
print('个人所得税: ¥%.2f元' % tax) print('个人所得税: ¥%.2f元' % tax)
print('实际到手收入: ¥%.2f元' % (diff + 3500 - tax)) print('实际到手收入: ¥%.2f元' % (diff + 3500 - tax))
""" """
判断输入的边长能否构成三角形 判断输入的边长能否构成三角形
如果能则计算出三角形的周长和面积 如果能则计算出三角形的周长和面积
Version: 0.1 Version: 0.1
Author: 骆昊 Author: 骆昊
Date: 2018-02-28 Date: 2018-02-28
""" """
import math import math
...@@ -15,9 +13,9 @@ a = float(input('a = ')) ...@@ -15,9 +13,9 @@ a = float(input('a = '))
b = float(input('b = ')) b = float(input('b = '))
c = float(input('c = ')) c = float(input('c = '))
if a + b > c and a + c > b and b + c > a: if a + b > c and a + c > b and b + c > a:
print('周长: %f' % (a + b + c)) print('周长: %f' % (a + b + c))
p = (a + b + c) / 2 p = (a + b + c) / 2
area = math.sqrt(p * (p - a) * (p - b) * (p - c)) area = math.sqrt(p * (p - a) * (p - b) * (p - c))
print('面积: %f' % (area)) print('面积: %f' % (area))
else: else:
print('不能构成三角形') print('不能构成三角形')
""" """
用户身份验证 用户身份验证
Version: 0.1 Version: 0.1
Author: 骆昊 Author: 骆昊
Date: 2018-02-28 Date: 2018-02-28
""" """
# import getpass # import getpass
...@@ -17,6 +15,6 @@ password = input('请输入口令: ') ...@@ -17,6 +15,6 @@ password = input('请输入口令: ')
# 输入口令的时候终端中没有回显 # 输入口令的时候终端中没有回显
# password = getpass.getpass('请输入口令: ') # password = getpass.getpass('请输入口令: ')
if username == 'admin' and password == '123456': if username == 'admin' and password == '123456':
print('身份验证成功!') print('身份验证成功!')
else: else:
print('身份验证失败!') print('身份验证失败!')
""" """
用for循环实现1~100求和 用for循环实现1~100求和
Version: 0.1 Version: 0.1
Author: 骆昊 Author: 骆昊
Date: 2018-03-01 Date: 2018-03-01
""" """
sum = 0 sum = 0
for x in range(1, 101): for x in range(1, 101):
if x % 2 == 0: if x % 2 == 0:
sum += x sum += x
print(sum) print(sum)
""" """
用for循环实现1~100之间的偶数求和 用for循环实现1~100之间的偶数求和
Version: 0.1 Version: 0.1
Author: 骆昊 Author: 骆昊
Date: 2018-03-01 Date: 2018-03-01
""" """
sum = 0 sum = 0
for x in range(2, 101, 2): for x in range(2, 101, 2):
sum += x sum += x
print(sum) print(sum)
""" """
输入非负整数n计算n! 输入非负整数n计算n!
Version: 0.1 Version: 0.1
Author: 骆昊 Author: 骆昊
Date: 2018-03-01 Date: 2018-03-01
""" """
n = int(input('n = ')) n = int(input('n = '))
result = 1 result = 1
for x in range(1, n + 1): for x in range(1, n + 1):
result *= x result *= x
print('%d! = %d' % (n, result)) print('%d! = %d' % (n, result))
""" """
输入一个正整数判断它是不是素数 输入一个正整数判断它是不是素数
Version: 0.1 Version: 0.1
Author: 骆昊 Author: 骆昊
Date: 2018-03-01 Date: 2018-03-01
""" """
from math import sqrt from math import sqrt
...@@ -14,10 +12,10 @@ num = int(input('请输入一个正整数: ')) ...@@ -14,10 +12,10 @@ num = int(input('请输入一个正整数: '))
end = int(sqrt(num)) end = int(sqrt(num))
is_prime = True is_prime = True
for x in range(2, end + 1): for x in range(2, end + 1):
if num % x == 0: if num % x == 0:
is_prime = False is_prime = False
break break
if is_prime and num != 1: if is_prime and num != 1:
print('%d是素数' % num) print('%d是素数' % num)
else: else:
print('%d不是素数' % num) print('%d不是素数' % num)
""" """
输入两个正整数计算最大公约数和最小公倍数 输入两个正整数计算最大公约数和最小公倍数
Version: 0.1 Version: 0.1
Author: 骆昊 Author: 骆昊
Date: 2018-03-01 Date: 2018-03-01
""" """
x = int(input('x = ')) x = int(input('x = '))
y = int(input('y = ')) y = int(input('y = '))
if x > y: if x > y:
(x, y) = (y, x) (x, y) = (y, x)
for factor in range(x, 0, -1): for factor in range(x, 0, -1):
if x % factor == 0 and y % factor == 0: if x % factor == 0 and y % factor == 0:
print('%d和%d的最大公约数是%d' % (x, y, factor)) print('%d和%d的最大公约数是%d' % (x, y, factor))
print('%d和%d的最小公倍数是%d' % (x, y, x * y // factor)) print('%d和%d的最小公倍数是%d' % (x, y, x * y // factor))
break break
""" """
打印各种三角形图案 打印各种三角形图案
* *
...@@ -23,7 +22,6 @@ ...@@ -23,7 +22,6 @@
Version: 0.1 Version: 0.1
Author: 骆昊 Author: 骆昊
Date: 2018-03-01 Date: 2018-03-01
""" """
row = int(input('请输入行数: ')) row = int(input('请输入行数: '))
......
""" """
用while循环实现1~100求和 用while循环实现1~100求和
Version: 0.1 Version: 0.1
Author: 骆昊 Author: 骆昊
Date: 2018-03-01 Date: 2018-03-01
""" """
sum = 0 sum = 0
num = 1 num = 1
while num <= 100: while num <= 100:
sum += num sum += num
num += 1 num += 1
print(sum) print(sum)
""" """
用while循环实现1~100之间的偶数求和 用while循环实现1~100之间的偶数求和
Version: 0.1 Version: 0.1
Author: 骆昊 Author: 骆昊
Date: 2018-03-01 Date: 2018-03-01
""" """
sum = 0 sum = 0
num = 2 num = 2
while num <= 100: while num <= 100:
sum += num sum += num
num += 2 num += 2
print(sum) print(sum)
""" """
求解《百钱百鸡》问题 求解《百钱百鸡》问题
1只公鸡5元 1只母鸡3元 3只小鸡1元 用100元买100只鸡 1只公鸡5元 1只母鸡3元 3只小鸡1元 用100元买100只鸡
问公鸡 母鸡 小鸡各有多少只 问公鸡 母鸡 小鸡各有多少只
...@@ -7,13 +6,12 @@ ...@@ -7,13 +6,12 @@
Version: 0.1 Version: 0.1
Author: 骆昊 Author: 骆昊
Date: 2018-03-02 Date: 2018-03-02
""" """
for x in range(0, 20): for x in range(0, 20):
for y in range(0, 33): for y in range(0, 33):
z = 100 - x - y z = 100 - x - y
if 5 * x + 3 * y + z / 3 == 100: if 5 * x + 3 * y + z / 3 == 100:
print('公鸡: %d只, 母鸡: %d只, 小鸡: %d只' % (x, y, z)) print('公鸡: %d只, 母鸡: %d只, 小鸡: %d只' % (x, y, z))
# 要理解程序背后的算法 - 穷举法 # 要理解程序背后的算法 - 穷举法
""" """
Craps赌博游戏 Craps赌博游戏
玩家摇两颗色子 如果第一次摇出7点或11点 玩家胜 玩家摇两颗色子 如果第一次摇出7点或11点 玩家胜
如果摇出2点 3点 12点 庄家胜 其他情况游戏继续 如果摇出2点 3点 12点 庄家胜 其他情况游戏继续
...@@ -11,40 +10,39 @@ Craps赌博游戏 ...@@ -11,40 +10,39 @@ Craps赌博游戏
Version: 0.1 Version: 0.1
Author: 骆昊 Author: 骆昊
Date: 2018-03-02 Date: 2018-03-02
""" """
from random import randint from random import randint
money = 1000 money = 1000
while money > 0: while money > 0:
print('你的总资产为:', money) print('你的总资产为:', money)
needs_go_on = False needs_go_on = False
while True: while True:
debt = int(input('请下注: ')) debt = int(input('请下注: '))
if debt > 0 and debt <= money: if debt > 0 and debt <= money:
break break
first = randint(1, 6) + randint(1, 6) first = randint(1, 6) + randint(1, 6)
print('玩家摇出了%d点' % first) print('玩家摇出了%d点' % first)
if first == 7 or first == 11: if first == 7 or first == 11:
print('玩家胜!') print('玩家胜!')
money += debt money += debt
elif first == 2 or first == 3 or first == 12: elif first == 2 or first == 3 or first == 12:
print('庄家胜!') print('庄家胜!')
money -= debt money -= debt
else: else:
needs_go_on = True needs_go_on = True
while needs_go_on: while needs_go_on:
current = randint(1, 6) + randint(1, 6) current = randint(1, 6) + randint(1, 6)
print('玩家摇出了%d点' % current) print('玩家摇出了%d点' % current)
if current == 7: if current == 7:
print('庄家胜') print('庄家胜')
money -= debt money -= debt
needs_go_on = False needs_go_on = False
elif current == first: elif current == first:
print('玩家胜') print('玩家胜')
money += debt money += debt
needs_go_on = False needs_go_on = False
print('你破产了, 游戏结束!') print('你破产了, 游戏结束!')
""" """
输出斐波那契数列的前20个数 输出斐波那契数列的前20个数
1 1 2 3 5 8 13 21 ... 1 1 2 3 5 8 13 21 ...
Version: 0.1 Version: 0.1
Author: 骆昊 Author: 骆昊
Date: 2018-03-02 Date: 2018-03-02
""" """
a = 0 a = 0
b = 1 b = 1
for _ in range(20): for _ in range(20):
(a, b) = (b, a + b) (a, b) = (b, a + b)
print(a, end=' ') print(a, end=' ')
""" """
猜数字游戏 猜数字游戏
计算机出一个1~100之间的随机数由人来猜 计算机出一个1~100之间的随机数由人来猜
计算机根据人猜的数字分别给出提示大一点/小一点/猜对了 计算机根据人猜的数字分别给出提示大一点/小一点/猜对了
...@@ -7,7 +6,6 @@ ...@@ -7,7 +6,6 @@
Version: 0.1 Version: 0.1
Author: 骆昊 Author: 骆昊
Date: 2018-03-02 Date: 2018-03-02
""" """
import random import random
...@@ -15,15 +13,15 @@ import random ...@@ -15,15 +13,15 @@ import random
answer = random.randint(1, 100) answer = random.randint(1, 100)
counter = 0 counter = 0
while True: while True:
counter += 1 counter += 1
number = int(input('请输入: ')) number = int(input('请输入: '))
if number < answer: if number < answer:
print('大一点') print('大一点')
elif number > answer: elif number > answer:
print('小一点') print('小一点')
else: else:
print('恭喜你猜对了!') print('恭喜你猜对了!')
break break
print('你总共猜了%d次' % counter) print('你总共猜了%d次' % counter)
if counter > 7: if counter > 7:
print('你的智商余额明显不足') print('你的智商余额明显不足')
""" """
找出100~999之间的所有水仙花数 找出100~999之间的所有水仙花数
水仙花数是各位立方和等于这个数本身的数 水仙花数是各位立方和等于这个数本身的数
如: 153 = 1**3 + 5**3 + 3**3 如: 153 = 1**3 + 5**3 + 3**3
...@@ -7,12 +6,11 @@ ...@@ -7,12 +6,11 @@
Version: 0.1 Version: 0.1
Author: 骆昊 Author: 骆昊
Date: 2018-03-02 Date: 2018-03-02
""" """
for num in range(100, 1000): for num in range(100, 1000):
low = num % 10 low = num % 10
mid = num // 10 % 10 mid = num // 10 % 10
high = num // 100 high = num // 100
if num == low ** 3 + mid ** 3 + high ** 3: if num == low ** 3 + mid ** 3 + high ** 3:
print(num) print(num)
""" """
判断输入的正整数是不是回文数 判断输入的正整数是不是回文数
回文数是指将一个正整数从左往右排列和从右往左排列值一样的数 回文数是指将一个正整数从左往右排列和从右往左排列值一样的数
Version: 0.1 Version: 0.1
Author: 骆昊 Author: 骆昊
Date: 2018-03-02 Date: 2018-03-02
""" """
num = int(input('请输入一个正整数: ')) num = int(input('请输入一个正整数: '))
temp = num temp = num
num2 = 0 num2 = 0
while temp > 0: while temp > 0:
num2 *= 10 num2 *= 10
num2 += temp % 10 num2 += temp % 10
temp //= 10 temp //= 10
if num == num2: if num == num2:
print('%d是回文数' % num) print('%d是回文数' % num)
else: else:
print('%d不是回文数' % num) print('%d不是回文数' % num)
""" """
找出1~9999之间的所有完美数 找出1~9999之间的所有完美数
完美数是除自身外其他所有因子的和正好等于这个数本身的数 完美数是除自身外其他所有因子的和正好等于这个数本身的数
例如: 6 = 1 + 2 + 3, 28 = 1 + 2 + 4 + 7 + 14 例如: 6 = 1 + 2 + 3, 28 = 1 + 2 + 4 + 7 + 14
...@@ -7,21 +6,20 @@ ...@@ -7,21 +6,20 @@
Version: 0.1 Version: 0.1
Author: 骆昊 Author: 骆昊
Date: 2018-03-02 Date: 2018-03-02
""" """
import time import time
import math import math
start = time.clock() start = time.clock()
for num in range(1, 10000): for num in range(1, 10000):
sum = 0 sum = 0
for factor in range(1, int(math.sqrt(num)) + 1): for factor in range(1, int(math.sqrt(num)) + 1):
if num % factor == 0: if num % factor == 0:
sum += factor sum += factor
if factor > 1 and num / factor != factor: if factor > 1 and num / factor != factor:
sum += num / factor sum += num / factor
if sum == num: if sum == num:
print(num) print(num)
end = time.clock() end = time.clock()
print("执行时间:", (end - start), "秒") print("执行时间:", (end - start), "秒")
......
""" """
输出2~99之间的素数 输出2~99之间的素数
Version: 0.1 Version: 0.1
Author: 骆昊 Author: 骆昊
Date: 2018-03-02 Date: 2018-03-02
""" """
import math import math
for num in range(2, 100): for num in range(2, 100):
is_prime = True is_prime = True
for factor in range(2, int(math.sqrt(num)) + 1): for factor in range(2, int(math.sqrt(num)) + 1):
if num % factor == 0: if num % factor == 0:
is_prime = False is_prime = False
break break
if is_prime: if is_prime:
print(num, end=' ') print(num, end=' ')
""" """
输出乘法口诀表(九九表) 输出乘法口诀表(九九表)
Version: 0.1 Version: 0.1
Author: 骆昊 Author: 骆昊
Date: 2018-03-02 Date: 2018-03-02
""" """
for i in range(1, 10): for i in range(1, 10):
for j in range(1, i + 1): for j in range(1, i + 1):
print('%d*%d=%d' % (i, j, i * j), end='\t') print('%d*%d=%d' % (i, j, i * j), end='\t')
print() print()
""" """
函数的定义和使用 - 计算组合数C(7,3) 函数的定义和使用 - 计算组合数C(7,3)
Version: 0.1 Version: 0.1
Author: 骆昊 Author: 骆昊
Date: 2018-03-05 Date: 2018-03-05
""" """
# 将求阶乘的功能封装成一个函数 # 将求阶乘的功能封装成一个函数
def factorial(n): def factorial(n):
result = 1 result = 1
for num in range(1, n + 1): for num in range(1, n + 1):
result *= num result *= num
return result return result
print(factorial(7) // factorial(3) // factorial(4)) print(factorial(7) // factorial(3) // factorial(4))
""" """
函数的定义和使用 - 求最大公约数和最小公倍数 函数的定义和使用 - 求最大公约数和最小公倍数
Version: 0.1 Version: 0.1
Author: 骆昊 Author: 骆昊
Date: 2018-03-05 Date: 2018-03-05
""" """
def gcd(x, y): def gcd(x, y):
if x > y: if x > y:
(x, y) = (y, x) (x, y) = (y, x)
for factor in range(x, 1, -1): for factor in range(x, 1, -1):
if x % factor == 0 and y % factor == 0: if x % factor == 0 and y % factor == 0:
return factor return factor
return 1 return 1
def lcm(x, y): def lcm(x, y):
return x * y // gcd(x, y) return x * y // gcd(x, y)
print(gcd(15, 27)) print(gcd(15, 27))
......
""" """
Python的内置函数 Python的内置函数
- 数学相关: abs / divmod / pow / round / min / max / sum - 数学相关: abs / divmod / pow / round / min / max / sum
- 序列相关: len / range / next / filter / map / sorted / slice / reversed - 序列相关: len / range / next / filter / map / sorted / slice / reversed
- 类型转换: chr / ord / str / bool / int / float / complex / bin / oct / hex - 类型转换: chr / ord / str / bool / int / float / complex / bin / oct / hex
- 数据结构: dict / list / set / tuple - 数据结构: dict / list / set / tuple
- 其他函数: all / any / id / input / open / print / type - 其他函数: all / any / id / input / open / print / type
Version: 0.1 Version: 0.1
Author: 骆昊 Author: 骆昊
Date: 2018-03-05 Date: 2018-03-05
""" """
def myfilter(mystr): def myfilter(mystr):
return len(mystr) == 6 return len(mystr) == 6
# help() # help()
......
""" """
Python常用模块 Python常用模块
- 运行时服务相关模块: copy / pickle / sys / ... - 运行时服务相关模块: copy / pickle / sys / ...
- 数学相关模块: decimal / math / random / ... - 数学相关模块: decimal / math / random / ...
- 字符串处理模块: codecs / re / ... - 字符串处理模块: codecs / re / ...
- 文件处理相关模块: shutil / gzip / ... - 文件处理相关模块: shutil / gzip / ...
- 操作系统服务相关模块: datetime / os / time / logging / io / ... - 操作系统服务相关模块: datetime / os / time / logging / io / ...
- 进程和线程相关模块: multiprocessing / threading / queue - 进程和线程相关模块: multiprocessing / threading / queue
- 网络应用相关模块: ftplib / http / smtplib / urllib / ... - 网络应用相关模块: ftplib / http / smtplib / urllib / ...
- Web编程相关模块: cgi / webbrowser - Web编程相关模块: cgi / webbrowser
- 数据处理和编码模块: base64 / csv / html.parser / json / xml / ... - 数据处理和编码模块: base64 / csv / html.parser / json / xml / ...
Version: 0.1 Version: 0.1
Author: 骆昊 Author: 骆昊
Date: 2018-03-05 Date: 2018-03-05
""" """
import time import time
......
""" """
函数的参数 函数的参数
- 默认参数 - 位置参数
- 可变参数 - 可变参数
- 关键字参数 - 关键字参数
- 命名关键字参数 - 命名关键字参数
Version: 0.1 Version: 0.1
Author: 骆昊 Author: 骆昊
Date: 2018-03-05 Date: 2018-03-05
""" """
# 参数默认值 # 参数默认值
def f1(a, b=5, c=10): def f1(a, b=5, c=10):
return a + b * 2 + c * 3 return a + b * 2 + c * 3
print(f1(1, 2, 3)) print(f1(1, 2, 3))
...@@ -26,10 +24,10 @@ print(f1(c=2, b=3, a=1)) ...@@ -26,10 +24,10 @@ print(f1(c=2, b=3, a=1))
# 可变参数 # 可变参数
def f2(*args): def f2(*args):
sum = 0 sum = 0
for num in args: for num in args:
sum += num sum += num
return sum return sum
print(f2(1, 2, 3)) print(f2(1, 2, 3))
...@@ -39,12 +37,12 @@ print(f2()) ...@@ -39,12 +37,12 @@ print(f2())
# 关键字参数 # 关键字参数
def f3(**kw): def f3(**kw):
if 'name' in kw: if 'name' in kw:
print('欢迎你%s!' % kw['name']) print('欢迎你%s!' % kw['name'])
elif 'tel' in kw: elif 'tel' in kw:
print('你的联系电话是: %s!' % kw['tel']) print('你的联系电话是: %s!' % kw['tel'])
else: else:
print('没找到你的个人信息!') print('没找到你的个人信息!')
param = {'name': '骆昊', 'age': 38} param = {'name': '骆昊', 'age': 38}
......
""" """
作用域问题 作用域问题
Version: 0.1 Version: 0.1
Author: 骆昊 Author: 骆昊
Date: 2018-03-05 Date: 2018-03-05
""" """
# 局部作用域 # 局部作用域
def foo1(): def foo1():
a = 5 a = 5
foo1() foo1()
# print(a) # NameError # print(a) # NameError
# 全局作用域 # 全局作用域
b = 10 b = 10
def foo2(): def foo2():
print(b) print(b)
foo2() foo2()
def foo3(): def foo3():
b = 100 # 局部变量 b = 100 # 局部变量
print(b) print(b)
foo3() foo3()
...@@ -38,9 +36,9 @@ print(b) ...@@ -38,9 +36,9 @@ print(b)
def foo4(): def foo4():
global b global b
b = 200 # 全局变量 b = 200 # 全局变量
print(b) print(b)
foo4() foo4()
......
...@@ -77,14 +77,14 @@ def roll_dice(n=2): ...@@ -77,14 +77,14 @@ def roll_dice(n=2):
:param n: 色子的个数 :param n: 色子的个数
:return: n颗色子点数之和 :return: n颗色子点数之和
""" """
total = 0 total = 0
for _ in range(n): for _ in range(n):
total += randint(1, 6) total += randint(1, 6)
return total return total
def add(a=0, b=0, c=0): def add(a=0, b=0, c=0):
return a + b + c return a + b + c
# 如果没有指定参数那么使用默认值摇两颗色子 # 如果没有指定参数那么使用默认值摇两颗色子
...@@ -107,10 +107,10 @@ print(add(c=50, a=100, b=200)) ...@@ -107,10 +107,10 @@ print(add(c=50, a=100, b=200))
# 在参数名前面的*表示args是一个可变参数 # 在参数名前面的*表示args是一个可变参数
# 即在调用add函数时可以传入0个或多个参数 # 即在调用add函数时可以传入0个或多个参数
def add(*args): def add(*args):
total = 0 total = 0
for val in args: for val in args:
total += val total += val
return total return total
print(add()) print(add())
...@@ -126,11 +126,11 @@ print(add(1, 3, 5, 7, 9)) ...@@ -126,11 +126,11 @@ print(add(1, 3, 5, 7, 9))
```Python ```Python
def foo(): def foo():
print('hello, world!') print('hello, world!')
def foo(): def foo():
print('goodbye, world!') print('goodbye, world!')
# 下面的代码会输出什么呢? # 下面的代码会输出什么呢?
...@@ -237,45 +237,45 @@ import module3 ...@@ -237,45 +237,45 @@ import module3
```Python ```Python
def gcd(x, y): def gcd(x, y):
(x, y) = (y, x) if x > y else (x, y) (x, y) = (y, x) if x > y else (x, y)
for factor in range(x, 0, -1): for factor in range(x, 0, -1):
if x % factor == 0 and y % factor == 0: if x % factor == 0 and y % factor == 0:
return factor return factor
def lcm(x, y): def lcm(x, y):
return x * y // gcd(x, y) return x * y // gcd(x, y)
``` ```
#### 练习2:实现判断一个数是不是回文数的函数。 #### 练习2:实现判断一个数是不是回文数的函数。
```Python ```Python
def is_palindrome(num): def is_palindrome(num):
temp = num temp = num
total = 0 total = 0
while temp > 0: while temp > 0:
total = total * 10 + temp % 10 total = total * 10 + temp % 10
temp //= 10 temp //= 10
return total == num return total == num
``` ```
#### 练习3:实现判断一个数是不是素数的函数。 #### 练习3:实现判断一个数是不是素数的函数。
```Python ```Python
def is_prime(num): def is_prime(num):
for factor in range(2, num): for factor in range(2, num):
if num % factor == 0: if num % factor == 0:
return False return False
return True if num != 1 else False return True if num != 1 else False
``` ```
#### 练习4:写一个程序判断输入的正整数是不是回文素数。 #### 练习4:写一个程序判断输入的正整数是不是回文素数。
```Python ```Python
if __name__ == '__main__': if __name__ == '__main__':
num = int(input('请输入正整数: ')) num = int(input('请输入正整数: '))
if is_palindrome(num) and is_prime(num): if is_palindrome(num) and is_prime(num):
print('%d是回文素数' % num) print('%d是回文素数' % num)
``` ```
通过上面的程序可以看出,当我们将代码中重复出现的和相对独立的功能抽取成函数后,我们可以组合使用这些函数来解决更为复杂的问题,这也是我们为什么要定义和使用函数的一个非常重要的原因。 通过上面的程序可以看出,当我们将代码中重复出现的和相对独立的功能抽取成函数后,我们可以组合使用这些函数来解决更为复杂的问题,这也是我们为什么要定义和使用函数的一个非常重要的原因。
...@@ -284,22 +284,22 @@ if __name__ == '__main__': ...@@ -284,22 +284,22 @@ if __name__ == '__main__':
```Python ```Python
def foo(): def foo():
b = 'hello' b = 'hello'
def bar(): # Python中可以在函数内部再定义函数 def bar(): # Python中可以在函数内部再定义函数
c = True c = True
print(a) print(a)
print(b) print(b)
print(c) print(c)
bar() bar()
# print(c) # NameError: name 'c' is not defined # print(c) # NameError: name 'c' is not defined
if __name__ == '__main__': if __name__ == '__main__':
a = 100 a = 100
# print(b) # NameError: name 'b' is not defined # print(b) # NameError: name 'b' is not defined
foo() foo()
``` ```
上面的代码能够顺利的执行并且打印出100和“hello”,但我们注意到了,在`bar`函数的内部并没有定义`a``b`两个变量,那么`a``b`是从哪里来的。我们在上面代码的`if`分支中定义了一个变量`a`,这是一个全局变量(global variable),属于全局作用域,因为它没有定义在任何一个函数中。在上面的`foo`函数中我们定义了变量`b`,这是一个定义在函数中的局部变量(local variable),属于局部作用域,在`foo`函数的外部并不能访问到它;但对于`foo`函数内部的`bar`函数来说,变量`b`属于嵌套作用域,在`bar`函数中我们是可以访问到它的。`bar`函数中的变量`c`属于局部作用域,在`bar`函数之外是无法访问的。事实上,Python查找一个变量时会按照“局部作用域”、“嵌套作用域”、“全局作用域”和“内置作用域”的顺序进行搜索,前三者我们在上面的代码中已经看到了,所谓的“内置作用域”就是Python内置的那些隐含标识符`min``len`等都属于内置作用域)。 上面的代码能够顺利的执行并且打印出100和“hello”,但我们注意到了,在`bar`函数的内部并没有定义`a``b`两个变量,那么`a``b`是从哪里来的。我们在上面代码的`if`分支中定义了一个变量`a`,这是一个全局变量(global variable),属于全局作用域,因为它没有定义在任何一个函数中。在上面的`foo`函数中我们定义了变量`b`,这是一个定义在函数中的局部变量(local variable),属于局部作用域,在`foo`函数的外部并不能访问到它;但对于`foo`函数内部的`bar`函数来说,变量`b`属于嵌套作用域,在`bar`函数中我们是可以访问到它的。`bar`函数中的变量`c`属于局部作用域,在`bar`函数之外是无法访问的。事实上,Python查找一个变量时会按照“局部作用域”、“嵌套作用域”、“全局作用域”和“内置作用域”的顺序进行搜索,前三者我们在上面的代码中已经看到了,所谓的“内置作用域”就是Python内置的那些隐含标识符`min``len`等都属于内置作用域)。
...@@ -308,29 +308,29 @@ if __name__ == '__main__': ...@@ -308,29 +308,29 @@ if __name__ == '__main__':
```Python ```Python
def foo(): def foo():
a = 200 a = 200
print(a) # 200 print(a) # 200
if __name__ == '__main__': if __name__ == '__main__':
a = 100 a = 100
foo() foo()
print(a) # 100 print(a) # 100
``` ```
在调用`foo`函数后,我们发现`a`的值仍然是100,这是因为当我们在函数`foo`中写`a = 200`的时候,是重新定义了一个名字为`a`的局部变量,它跟全局作用域的`a`并不是同一个变量,因为局部作用域中有了自己的变量`a`,因此`foo`函数不再搜索全局作用域中的`a`。如果我们希望在`foo`函数中修改全局作用域中的`a`,代码如下所示。 在调用`foo`函数后,我们发现`a`的值仍然是100,这是因为当我们在函数`foo`中写`a = 200`的时候,是重新定义了一个名字为`a`的局部变量,它跟全局作用域的`a`并不是同一个变量,因为局部作用域中有了自己的变量`a`,因此`foo`函数不再搜索全局作用域中的`a`。如果我们希望在`foo`函数中修改全局作用域中的`a`,代码如下所示。
```Python ```Python
def foo(): def foo():
global a global a
a = 200 a = 200
print(a) # 200 print(a) # 200
if __name__ == '__main__': if __name__ == '__main__':
a = 100 a = 100
foo() foo()
print(a) # 200 print(a) # 200
``` ```
我们可以使用`global`关键字来指示`foo`函数中的变量`a`来自于全局作用域,如果全局作用域中没有`a`,那么下面一行的代码就会定义变量`a`并将其置于全局作用域。同理,如果我们希望函数内部的函数能够修改嵌套作用域中的变量,可以使用`nonlocal`关键字来指示变量来自于嵌套作用域,请大家自行试验。 我们可以使用`global`关键字来指示`foo`函数中的变量`a`来自于全局作用域,如果全局作用域中没有`a`,那么下面一行的代码就会定义变量`a`并将其置于全局作用域。同理,如果我们希望函数内部的函数能够修改嵌套作用域中的变量,可以使用`nonlocal`关键字来指示变量来自于嵌套作用域,请大家自行试验。
...@@ -350,4 +350,3 @@ def main(): ...@@ -350,4 +350,3 @@ def main():
if __name__ == '__main__': if __name__ == '__main__':
main() main()
``` ```
""" """
输入学生考试成绩计算平均分 输入学生考试成绩计算平均分
Version: 0.1 Version: 0.1
Author: 骆昊 Author: 骆昊
Date: 2018-03-06 Date: 2018-03-06
""" """
def main(): def main():
number = int(input('请输入学生人数: ')) number = int(input('请输入学生人数: '))
names = [None] * number names = [None] * number
scores = [None] * number scores = [None] * number
for index in range(len(names)): for index in range(len(names)):
names[index] = input('请输入第%d个学生的名字: ' % (index + 1)) names[index] = input('请输入第%d个学生的名字: ' % (index + 1))
scores[index] = float(input('请输入第%d个学生的成绩: ' % (index + 1))) scores[index] = float(input('请输入第%d个学生的成绩: ' % (index + 1)))
total = 0 total = 0
for index in range(len(names)): for index in range(len(names)):
print('%s: %.1f分' % (names[index], scores[index])) print('%s: %.1f分' % (names[index], scores[index]))
total += scores[index] total += scores[index]
print('平均成绩是: %.1f分' % (total / number)) print('平均成绩是: %.1f分' % (total / number))
if __name__ == '__main__': if __name__ == '__main__':
main() main()
""" """
定义和使用字典 定义和使用字典
Version: 0.1 Version: 0.1
Author: 骆昊 Author: 骆昊
Date: 2018-03-06 Date: 2018-03-06
""" """
def main(): def main():
scores = {'骆昊': 95, '白元芳': 78, '狄仁杰': 82} scores = {'骆昊': 95, '白元芳': 78, '狄仁杰': 82}
print(scores['骆昊']) print(scores['骆昊'])
print(scores['狄仁杰']) print(scores['狄仁杰'])
for elem in scores: for elem in scores:
print('%s\t--->\t%d' % (elem, scores[elem])) print('%s\t--->\t%d' % (elem, scores[elem]))
scores['白元芳'] = 65 scores['白元芳'] = 65
scores['诸葛王朗'] = 71 scores['诸葛王朗'] = 71
scores.update(冷面=67, 方启鹤=85) scores.update(冷面=67, 方启鹤=85)
print(scores) print(scores)
if '武则天' in scores: if '武则天' in scores:
print(scores['武则天']) print(scores['武则天'])
print(scores.get('武则天')) print(scores.get('武则天'))
print(scores.get('武则天', 60)) print(scores.get('武则天', 60))
print(scores.popitem()) print(scores.popitem())
print(scores.popitem()) print(scores.popitem())
print(scores.pop('骆昊', 100)) print(scores.pop('骆昊', 100))
scores.clear() scores.clear()
print(scores) print(scores)
if __name__ == '__main__': if __name__ == '__main__':
main() main()
""" """
字典的常用操作 字典的常用操作
Version: 0.1 Version: 0.1
Author: 骆昊 Author: 骆昊
Date: 2018-03-06 Date: 2018-03-06
""" """
def main(): def main():
stu = {'name': '骆昊', 'age': 38, 'gender': True} stu = {'name': '骆昊', 'age': 38, 'gender': True}
print(stu) print(stu)
print(stu.keys()) print(stu.keys())
print(stu.values()) print(stu.values())
print(stu.items()) print(stu.items())
for elem in stu.items(): for elem in stu.items():
print(elem) print(elem)
print(elem[0], elem[1]) print(elem[0], elem[1])
if 'age' in stu: if 'age' in stu:
stu['age'] = 20 stu['age'] = 20
print(stu) print(stu)
stu.setdefault('score', 60) stu.setdefault('score', 60)
print(stu) print(stu)
stu.setdefault('score', 100) stu.setdefault('score', 100)
print(stu) print(stu)
stu['score'] = 100 stu['score'] = 100
print(stu) print(stu)
if __name__ == '__main__': if __name__ == '__main__':
main() main()
""" """
生成斐波拉切数列 生成斐波拉切数列
Version: 0.1 Version: 0.1
Author: 骆昊 Author: 骆昊
Date: 2018-03-06 Date: 2018-03-06
""" """
def main(): def main():
f = [1 , 1] f = [1 , 1]
for i in range(2, 20): for i in range(2, 20):
f += [f[i - 1] + f[i - 2]] f += [f[i - 1] + f[i - 2]]
# f.append(f[i - 1] + f[i - 2]) # f.append(f[i - 1] + f[i - 2])
for val in f: for val in f:
print(val, end=' ') print(val, end=' ')
if __name__ == '__main__': if __name__ == '__main__':
main() main()
""" """
找出列表中最大或最小的元素 找出列表中最大或最小的元素
Version: 0.1 Version: 0.1
Author: 骆昊 Author: 骆昊
Date: 2018-03-06 Date: 2018-03-06
""" """
def main(): def main():
fruits = ['grape', 'apple', 'strawberry', 'waxberry', 'pitaya'] fruits = ['grape', 'apple', 'strawberry', 'waxberry', 'pitaya']
# 直接使用内置的max和min函数找出列表中最大和最小元素 # 直接使用内置的max和min函数找出列表中最大和最小元素
# print(max(fruits)) # print(max(fruits))
# print(min(fruits)) # print(min(fruits))
max_value = min_value = fruits[0] max_value = min_value = fruits[0]
for index in range(1, len(fruits)): for index in range(1, len(fruits)):
if fruits[index] > max_value: if fruits[index] > max_value:
max_value = fruits[index] max_value = fruits[index]
elif fruits[index] < min_value: elif fruits[index] < min_value:
min_value = fruits[index] min_value = fruits[index]
print('Max:', max_value) print('Max:', max_value)
print('Min:', min_value) print('Min:', min_value)
if __name__ == '__main__': if __name__ == '__main__':
main() main()
# 想一想如果最大的元素有两个要找出第二大的又该怎么做 # 想一想如果最大的元素有两个要找出第二大的又该怎么做
""" """
定义和使用列表 定义和使用列表
- 用下标访问元素 - 用下标访问元素
- 添加元素 - 添加元素
- 删除元素 - 删除元素
Version: 0.1 Version: 0.1
Author: 骆昊 Author: 骆昊
Date: 2018-03-06 Date: 2018-03-06
""" """
def main(): def main():
fruits = ['grape', '@pple', 'strawberry', 'waxberry'] fruits = ['grape', '@pple', 'strawberry', 'waxberry']
print(fruits) print(fruits)
# 通过下标访问元素 # 通过下标访问元素
print(fruits[0]) print(fruits[0])
print(fruits[1]) print(fruits[1])
print(fruits[-1]) print(fruits[-1])
print(fruits[-2]) print(fruits[-2])
# print(fruits[-5]) # IndexError # print(fruits[-5]) # IndexError
# print(fruits[4]) # IndexError # print(fruits[4]) # IndexError
fruits[1] = 'apple' fruits[1] = 'apple'
print(fruits) print(fruits)
# 添加元素 # 添加元素
fruits.append('pitaya') fruits.append('pitaya')
fruits.insert(0, 'banana') fruits.insert(0, 'banana')
print(fruits) print(fruits)
# 删除元素 # 删除元素
del fruits[1] del fruits[1]
fruits.pop() fruits.pop()
fruits.pop(0) fruits.pop(0)
fruits.remove('apple') fruits.remove('apple')
print(fruits) print(fruits)
if __name__ == '__main__': if __name__ == '__main__':
main() main()
""" """
列表常用操作 列表常用操作
- 列表连接 - 列表连接
- 获取长度 - 获取长度
- 遍历列表 - 遍历列表
- 列表切片 - 列表切片
- 列表排序 - 列表排序
- 列表反转 - 列表反转
- 查找元素 - 查找元素
Version: 0.1 Version: 0.1
Author: 骆昊 Author: 骆昊
Date: 2018-03-06 Date: 2018-03-06
""" """
def main(): def main():
fruits = ['grape', 'apple', 'strawberry', 'waxberry'] fruits = ['grape', 'apple', 'strawberry', 'waxberry']
fruits += ['pitaya', 'pear', 'mango'] fruits += ['pitaya', 'pear', 'mango']
# 循环遍历列表元素 # 循环遍历列表元素
for fruit in fruits: for fruit in fruits:
print(fruit.title(), end=' ') print(fruit.title(), end=' ')
print() print()
# 列表切片 # 列表切片
fruits2 = fruits[1:4] fruits2 = fruits[1:4]
print(fruits2) print(fruits2)
# fruit3 = fruits # 没有复制列表只创建了新的引用 # fruit3 = fruits # 没有复制列表只创建了新的引用
fruits3 = fruits[:] fruits3 = fruits[:]
print(fruits3) print(fruits3)
fruits4 = fruits[-3:-1] fruits4 = fruits[-3:-1]
print(fruits4) print(fruits4)
fruits5 = fruits[::-1] fruits5 = fruits[::-1]
print(fruits5) print(fruits5)
if __name__ == '__main__': if __name__ == '__main__':
main() main()
""" """
生成列表 生成列表
- 用range创建数字列表 - 用range创建数字列表
- 生成表达式 - 生成表达式
- 生成器 - 生成器
Version: 0.1 Version: 0.1
Author: 骆昊 Author: 骆昊
Date: 2018-03-06 Date: 2018-03-06
""" """
# 生成Fibonacci序列的生成器 # 生成Fibonacci序列的生成器
def fib(n): def fib(n):
a, b = 0, 1 a, b = 0, 1
for _ in range(n): for _ in range(n):
a, b = b, a + b a, b = b, a + b
yield a yield a
def main(): def main():
# 用range创建数值列表 # 用range创建数值列表
list1 = list(range(1, 11)) list1 = list(range(1, 11))
print(list1) print(list1)
# 生成表达式 # 生成表达式
list2 = [x * x for x in range(1, 11)] list2 = [x * x for x in range(1, 11)]
print(list2) print(list2)
list3 = [m + n for m in 'ABCDEFG' for n in '12345'] list3 = [m + n for m in 'ABCDEFG' for n in '12345']
print(list3) print(list3)
print(len(list3)) print(len(list3))
# 生成器(节省空间但生成下一个元素时需要花费时间) # 生成器(节省空间但生成下一个元素时需要花费时间)
gen = (m + n for m in 'ABCDEFG' for n in '12345') gen = (m + n for m in 'ABCDEFG' for n in '12345')
print(gen) print(gen)
for elem in gen: for elem in gen:
print(elem, end=' ') print(elem, end=' ')
print() print()
gen = fib(20) gen = fib(20)
print(gen) print(gen)
for elem in gen: for elem in gen:
print(elem, end=' ') print(elem, end=' ')
print() print()
if __name__ == '__main__': if __name__ == '__main__':
main() main()
""" """
双色球随机选号程序 双色球随机选号程序
Version: 0.1 Version: 0.1
Author: 骆昊 Author: 骆昊
Date: 2018-03-06 Date: 2018-03-06
""" """
from random import randrange, randint, sample from random import randrange, randint, sample
def display(balls): def display(balls):
""" """
输出列表中的双色球号码 输出列表中的双色球号码
""" """
for index, ball in enumerate(balls): for index, ball in enumerate(balls):
if index == len(balls) - 1: if index == len(balls) - 1:
print('|', end=' ') print('|', end=' ')
print('%02d' % ball, end=' ') print('%02d' % ball, end=' ')
print() print()
def random_select(): def random_select():
""" """
随机选择一组号码 随机选择一组号码
""" """
red_balls = [x for x in range(1, 34)] red_balls = [x for x in range(1, 34)]
selected_balls = [] selected_balls = []
for _ in range(6): for _ in range(6):
index = randrange(len(red_balls)) index = randrange(len(red_balls))
selected_balls.append(red_balls[index]) selected_balls.append(red_balls[index])
del red_balls[index] del red_balls[index]
# 上面的for循环也可以写成下面这行代码 # 上面的for循环也可以写成下面这行代码
# sample函数是random模块下的函数 # sample函数是random模块下的函数
# selected_balls = sample(red_balls, 6) # selected_balls = sample(red_balls, 6)
selected_balls.sort() selected_balls.sort()
selected_balls.append(randint(1, 16)) selected_balls.append(randint(1, 16))
return selected_balls return selected_balls
def main(): def main():
n = int(input('机选几注: ')) n = int(input('机选几注: '))
for _ in range(n): for _ in range(n):
display(random_select()) display(random_select())
if __name__ == '__main__': if __name__ == '__main__':
main() main()
""" """
输入学生考试成绩计算平均分 输入学生考试成绩计算平均分
Version: 0.1 Version: 0.1
Author: 骆昊 Author: 骆昊
Date: 2018-03-06 Date: 2018-03-06
""" """
import os import os
...@@ -13,14 +11,14 @@ import time ...@@ -13,14 +11,14 @@ import time
def main(): def main():
str = 'Welcome to 1000 Phone Chengdu Campus ' str = 'Welcome to 1000 Phone Chengdu Campus '
while True: while True:
print(str) print(str)
time.sleep(0.2) time.sleep(0.2)
str = str[1:] + str[0:1] str = str[1:] + str[0:1]
# for Windows use os.system('cls') instead # for Windows use os.system('cls') instead
os.system('clear') os.system('clear')
if __name__ == '__main__': if __name__ == '__main__':
main() main()
""" """
学生考试成绩表 学生考试成绩表
Version: 0.1 Version: 0.1
Author: 骆昊 Author: 骆昊
Date: 2018-03-06 Date: 2018-03-06
""" """
def main(): def main():
names = ['关羽', '张飞', '赵云', '马超', '黄忠'] names = ['关羽', '张飞', '赵云', '马超', '黄忠']
subjs = ['语文', '数学', '英语'] subjs = ['语文', '数学', '英语']
scores = [[0] * 3] * 5 scores = [[0] * 3] * 5
for row, name in enumerate(names): for row, name in enumerate(names):
print('请输入%s的成绩' % name) print('请输入%s的成绩' % name)
for col, subj in enumerate(subjs): for col, subj in enumerate(subjs):
scores[row][col] = float(input(subj + ': ')) scores[row][col] = float(input(subj + ': '))
print(scores) print(scores)
# for row, name in enumerate(names): # for row, name in enumerate(names):
# print('请输入%s的成绩' % name) # print('请输入%s的成绩' % name)
# scores[row] = [None] * len(subjs) # scores[row] = [None] * len(subjs)
# for col, subj in enumerate(subjs): # for col, subj in enumerate(subjs):
# score = float(input(subj + ': ')) # score = float(input(subj + ': '))
# scores[row][col] = score # scores[row][col] = score
# print(scores) # print(scores)
if __name__ == '__main__': if __name__ == '__main__':
main() main()
""" """
定义和使用集合 定义和使用集合
Version: 0.1 Version: 0.1
Author: 骆昊 Author: 骆昊
Date: 2018-03-06 Date: 2018-03-06
""" """
......
""" """
集合的常用操作 集合的常用操作
- 交集 - 交集
- 并集 - 并集
- 差集 - 差集
- 子集 - 子集
- 超集 - 超集
Version: 0.1 Version: 0.1
Author: 骆昊 Author: 骆昊
Date: 2018-03-06 Date: 2018-03-06
""" """
def main(): def main():
set1 = set(range(1, 7)) set1 = set(range(1, 7))
print(set1) print(set1)
set2 = set(range(2, 11, 2)) set2 = set(range(2, 11, 2))
print(set2) print(set2)
set3 = set(range(1, 5)) set3 = set(range(1, 5))
print(set1 & set2) print(set1 & set2)
# print(set1.intersection(set2)) # print(set1.intersection(set2))
print(set1 | set2) print(set1 | set2)
# print(set1.union(set2)) # print(set1.union(set2))
print(set1 - set2) print(set1 - set2)
# print(set1.difference(set2)) # print(set1.difference(set2))
print(set1 ^ set2) print(set1 ^ set2)
# print(set1.symmetric_difference(set2)) # print(set1.symmetric_difference(set2))
print(set2 <= set1) print(set2 <= set1)
# print(set2.issubset(set1)) # print(set2.issubset(set1))
print(set3 <= set1) print(set3 <= set1)
# print(set3.issubset(set1)) # print(set3.issubset(set1))
print(set1 >= set2) print(set1 >= set2)
# print(set1.issuperset(set2)) # print(set1.issuperset(set2))
print(set1 >= set3) print(set1 >= set3)
# print(set1.issuperset(set3)) # print(set1.issuperset(set3))
if __name__ == '__main__': if __name__ == '__main__':
main() main()
""" """
井字棋游戏 井字棋游戏
Version: 0.1 Version: 0.1
Author: 骆昊 Author: 骆昊
Date: 2018-03-06 Date: 2018-03-06
""" """
import os import os
...@@ -13,41 +11,41 @@ import os ...@@ -13,41 +11,41 @@ import os
def print_board(board): def print_board(board):
print(board['TL'] + '|' + board['TM'] + '|' + board['TR']) print(board['TL'] + '|' + board['TM'] + '|' + board['TR'])
print('-+-+-') print('-+-+-')
print(board['ML'] + '|' + board['MM'] + '|' + board['MR']) print(board['ML'] + '|' + board['MM'] + '|' + board['MR'])
print('-+-+-') print('-+-+-')
print(board['BL'] + '|' + board['BM'] + '|' + board['BR']) print(board['BL'] + '|' + board['BM'] + '|' + board['BR'])
def main(): def main():
init_board = { init_board = {
'TL': ' ', 'TM': ' ', 'TR': ' ', 'TL': ' ', 'TM': ' ', 'TR': ' ',
'ML': ' ', 'MM': ' ', 'MR': ' ', 'ML': ' ', 'MM': ' ', 'MR': ' ',
'BL': ' ', 'BM': ' ', 'BR': ' ' 'BL': ' ', 'BM': ' ', 'BR': ' '
} }
begin = True begin = True
while begin: while begin:
curr_board = init_board.copy() curr_board = init_board.copy()
begin = False begin = False
turn = 'x' turn = 'x'
counter = 0 counter = 0
os.system('clear') os.system('clear')
print_board(curr_board) print_board(curr_board)
while counter < 9: while counter < 9:
move = input('轮到%s走棋, 请输入位置: ' % turn) move = input('轮到%s走棋, 请输入位置: ' % turn)
if curr_board[move] == ' ': if curr_board[move] == ' ':
counter += 1 counter += 1
curr_board[move] = turn curr_board[move] = turn
if turn == 'x': if turn == 'x':
turn = 'o' turn = 'o'
else: else:
turn = 'x' turn = 'x'
os.system('clear') os.system('clear')
print_board(curr_board) print_board(curr_board)
choice = input('再玩一局?(yes|no)') choice = input('再玩一局?(yes|no)')
begin = choice == 'yes' begin = choice == 'yes'
if __name__ == '__main__': if __name__ == '__main__':
main() main()
""" """
元组的定义和使用 元组的定义和使用
Version: 0.1 Version: 0.1
Author: 骆昊 Author: 骆昊
Date: 2018-03-06 Date: 2018-03-06
""" """
def main(): def main():
# 定义元组 # 定义元组
t = ('骆昊', 38, True, '四川成都') t = ('骆昊', 38, True, '四川成都')
print(t) print(t)
# 获取元组中的元素 # 获取元组中的元素
print(t[0]) print(t[0])
print(t[1]) print(t[1])
print(t[2]) print(t[2])
print(t[3]) print(t[3])
# 遍历元组中的值 # 遍历元组中的值
for member in t: for member in t:
print(member) print(member)
# 重新给元组赋值 # 重新给元组赋值
# t[0] = '王大锤' # TypeError # t[0] = '王大锤' # TypeError
# 变量t重新引用了新的元组 原来的元组被垃圾回收 # 变量t重新引用了新的元组 原来的元组被垃圾回收
t = ('王大锤', 20, True, '云南昆明') t = ('王大锤', 20, True, '云南昆明')
print(t) print(t)
# 元组和列表的转换 # 元组和列表的转换
person = list(t) person = list(t)
print(person) print(person)
person[0] = '李小龙' person[0] = '李小龙'
person[1] = 25 person[1] = 25
print(person) print(person)
fruits_list = ['apple', 'banana', 'orange'] fruits_list = ['apple', 'banana', 'orange']
fruits_tuple = tuple(fruits_list) fruits_tuple = tuple(fruits_list)
print(fruits_tuple) print(fruits_tuple)
print(fruits_tuple[1]) print(fruits_tuple[1])
if __name__ == '__main__': if __name__ == '__main__':
main() main()
\ No newline at end of file \ No newline at end of file
""" """
输出10行的杨辉三角 - 二项式的n次方展开系数 输出10行的杨辉三角 - 二项式的n次方展开系数
1 1
1 1 1 1
...@@ -12,7 +11,6 @@ ...@@ -12,7 +11,6 @@
Version: 0.1 Version: 0.1
Author: 骆昊 Author: 骆昊
Date: 2018-03-06 Date: 2018-03-06
""" """
......
class Test: class Test:
def __init__(self, foo): def __init__(self, foo):
self.__foo = foo self.__foo = foo
def __bar(self): def __bar(self):
print(self.__foo) print(self.__foo)
print('__bar') print('__bar')
def main(): def main():
test = Test('hello') test = Test('hello')
test._Test__bar() test._Test__bar()
print(test._Test__foo) print(test._Test__foo)
if __name__ == "__main__": if __name__ == "__main__":
main() main()
""" """
练习 练习
修一个游泳池 半径(以米为单位)在程序运行时输入 游泳池外修一条3米宽的过道 修一个游泳池 半径(以米为单位)在程序运行时输入 游泳池外修一条3米宽的过道
过道的外侧修一圈围墙 已知过道的造价为25元每平米 围墙的造价为32.5元每米 过道的外侧修一圈围墙 已知过道的造价为25元每平米 围墙的造价为32.5元每米
...@@ -8,7 +7,6 @@ ...@@ -8,7 +7,6 @@
Version: 0.1 Version: 0.1
Author: 骆昊 Author: 骆昊
Date: 2018-03-08 Date: 2018-03-08
""" """
import math import math
...@@ -16,29 +14,29 @@ import math ...@@ -16,29 +14,29 @@ import math
class Circle(object): class Circle(object):
def __init__(self, radius): def __init__(self, radius):
self._radius = radius self._radius = radius
@property @property
def radius(self): def radius(self):
return self._radius return self._radius
@radius.setter @radius.setter
def radius(self, radius): def radius(self, radius):
self._radius = radius if radius > 0 else 0 self._radius = radius if radius > 0 else 0
@property @property
def perimeter(self): def perimeter(self):
return 2 * math.pi * self._radius return 2 * math.pi * self._radius
@property @property
def area(self): def area(self):
return math.pi * self._radius * self._radius return math.pi * self._radius * self._radius
if __name__ == '__main__': if __name__ == '__main__':
radius = float(input('请输入游泳池的半径: ')) radius = float(input('请输入游泳池的半径: '))
small = Circle(radius) small = Circle(radius)
big = Circle(radius + 3) big = Circle(radius + 3)
print('围墙的造价为: ¥%.1f元' % (big.perimeter * 115)) print('围墙的造价为: ¥%.1f元' % (big.perimeter * 115))
print('过道的造价为: ¥%.1f元' % ((big.area - small.area) * 65)) print('过道的造价为: ¥%.1f元' % ((big.area - small.area) * 65))
""" """
定义和使用时钟类 定义和使用时钟类
Version: 0.1 Version: 0.1
Author: 骆昊 Author: 骆昊
Date: 2018-03-08 Date: 2018-03-08
""" """
import time import time
...@@ -14,40 +12,40 @@ import os ...@@ -14,40 +12,40 @@ import os
class Clock(object): class Clock(object):
# Python中的函数是没有重载的概念的 # Python中的函数是没有重载的概念的
# 因为Python中函数的参数没有类型而且支持缺省参数和可变参数 # 因为Python中函数的参数没有类型而且支持缺省参数和可变参数
# 用关键字参数让构造器可以传入任意多个参数来实现其他语言中的构造器重载 # 用关键字参数让构造器可以传入任意多个参数来实现其他语言中的构造器重载
def __init__(self, **kw): def __init__(self, **kw):
if 'hour' in kw and 'minute' in kw and 'second' in kw: if 'hour' in kw and 'minute' in kw and 'second' in kw:
self._hour = kw['hour'] self._hour = kw['hour']
self._minute = kw['minute'] self._minute = kw['minute']
self._second = kw['second'] self._second = kw['second']
else: else:
tm = time.localtime(time.time()) tm = time.localtime(time.time())
self._hour = tm.tm_hour self._hour = tm.tm_hour
self._minute = tm.tm_min self._minute = tm.tm_min
self._second = tm.tm_sec self._second = tm.tm_sec
def run(self): def run(self):
self._second += 1 self._second += 1
if self._second == 60: if self._second == 60:
self._second = 0 self._second = 0
self._minute += 1 self._minute += 1
if self._minute == 60: if self._minute == 60:
self._minute = 0 self._minute = 0
self._hour += 1 self._hour += 1
if self._hour == 24: if self._hour == 24:
self._hour = 0 self._hour = 0
def show(self): def show(self):
return '%02d:%02d:%02d' % (self._hour, self._minute, self._second) return '%02d:%02d:%02d' % (self._hour, self._minute, self._second)
if __name__ == '__main__': if __name__ == '__main__':
# clock = Clock(hour=10, minute=5, second=58) # clock = Clock(hour=10, minute=5, second=58)
clock = Clock() clock = Clock()
while True: while True:
os.system('clear') os.system('clear')
print(clock.show()) print(clock.show())
time.sleep(1) time.sleep(1)
clock.run() clock.run()
""" """
面向对象版本的猜数字游戏 面向对象版本的猜数字游戏
Version: 0.1 Version: 0.1
Author: 骆昊 Author: 骆昊
Date: 2018-03-08 Date: 2018-03-08
""" """
from random import randint from random import randint
...@@ -13,46 +11,46 @@ from random import randint ...@@ -13,46 +11,46 @@ from random import randint
class GuessMachine(object): class GuessMachine(object):
def __init__(self): def __init__(self):
self._answer = None self._answer = None
self._counter = None self._counter = None
self._hint = None self._hint = None
def reset(self): def reset(self):
self._answer = randint(1, 100) self._answer = randint(1, 100)
self._counter = 0 self._counter = 0
self._hint = None self._hint = None
def guess(self, your_answer): def guess(self, your_answer):
self._counter += 1 self._counter += 1
if your_answer > self._answer: if your_answer > self._answer:
self._hint = '小一点' self._hint = '小一点'
elif your_answer < self._answer: elif your_answer < self._answer:
self._hint = '大一点' self._hint = '大一点'
else: else:
self._hint = '恭喜你猜对了' self._hint = '恭喜你猜对了'
return True return True
return False return False
@property @property
def counter(self): def counter(self):
return self._counter return self._counter
@property @property
def hint(self): def hint(self):
return self._hint return self._hint
if __name__ == '__main__': if __name__ == '__main__':
gm = GuessMachine() gm = GuessMachine()
play_again = True play_again = True
while play_again: while play_again:
game_over = False game_over = False
gm.reset() gm.reset()
while not game_over: while not game_over:
your_answer = int(input('请输入: ')) your_answer = int(input('请输入: '))
game_over = gm.guess(your_answer) game_over = gm.guess(your_answer)
print(gm.hint) print(gm.hint)
if gm.counter > 7: if gm.counter > 7:
print('智商余额不足!') print('智商余额不足!')
play_again = input('再玩一次?(yes|no)') == 'yes' play_again = input('再玩一次?(yes|no)') == 'yes'
""" """
另一种创建类的方式 另一种创建类的方式
Version: 0.1 Version: 0.1
Author: 骆昊 Author: 骆昊
Date: 2018-03-08 Date: 2018-03-08
""" """
def bar(self, name): def bar(self, name):
self._name = name self._name = name
def foo(self, course_name): def foo(self, course_name):
print('%s正在学习%s.' % (self._name, course_name)) print('%s正在学习%s.' % (self._name, course_name))
def main(): def main():
Student = type('Student', (object,), dict(__init__=bar, study=foo)) Student = type('Student', (object,), dict(__init__=bar, study=foo))
stu1 = Student('骆昊') stu1 = Student('骆昊')
stu1.study('Python程序设计') stu1.study('Python程序设计')
if __name__ == '__main__': if __name__ == '__main__':
main() main()
""" """
定义和使用矩形类 定义和使用矩形类
Version: 0.1 Version: 0.1
Author: 骆昊 Author: 骆昊
Date: 2018-03-08 Date: 2018-03-08
""" """
class Rect(object): class Rect(object):
"""矩形类""" """矩形类"""
def __init__(self, width=0, height=0): def __init__(self, width=0, height=0):
"""构造器""" """构造器"""
self.__width = width self.__width = width
self.__height = height self.__height = height
def perimeter(self): def perimeter(self):
"""计算周长""" """计算周长"""
return (self.__width + self.__height) * 2 return (self.__width + self.__height) * 2
def area(self): def area(self):
"""计算面积""" """计算面积"""
return self.__width * self.__height return self.__width * self.__height
def __str__(self): def __str__(self):
"""矩形对象的字符串表达式""" """矩形对象的字符串表达式"""
return '矩形[%f,%f]' % (self.__width, self.__height) return '矩形[%f,%f]' % (self.__width, self.__height)
def __del__(self): def __del__(self):
"""析构器""" """析构器"""
print('销毁矩形对象') print('销毁矩形对象')
if __name__ == '__main__': if __name__ == '__main__':
rect1 = Rect() rect1 = Rect()
print(rect1) print(rect1)
print(rect1.perimeter()) print(rect1.perimeter())
print(rect1.area()) print(rect1.area())
rect2 = Rect(3.5, 4.5) rect2 = Rect(3.5, 4.5)
print(rect2) print(rect2)
print(rect2.perimeter()) print(rect2.perimeter())
print(rect2.area()) print(rect2.area())
""" """
定义和使用学生类 定义和使用学生类
Version: 0.1 Version: 0.1
Author: 骆昊 Author: 骆昊
Date: 2018-03-08 Date: 2018-03-08
""" """
def _foo(): def _foo():
print('test') print('test')
class Student(object): class Student(object):
# __init__是一个特殊方法用于在创建对象时进行初始化操作 # __init__是一个特殊方法用于在创建对象时进行初始化操作
# 通过这个方法我们可以为学生对象绑定name和age两个属性 # 通过这个方法我们可以为学生对象绑定name和age两个属性
def __init__(self, name, age): def __init__(self, name, age):
self.name = name self.name = name
self.age = age self.age = age
def study(self, course_name): def study(self, course_name):
print('%s正在学习%s.' % (self.name, course_name)) print('%s正在学习%s.' % (self.name, course_name))
# PEP 8要求标识符的名字用全小写多个单词用下划线连接 # PEP 8要求标识符的名字用全小写多个单词用下划线连接
# 但是很多程序员和公司更倾向于使用驼峰命名法(驼峰标识) # 但是很多程序员和公司更倾向于使用驼峰命名法(驼峰标识)
def watch_av(self): def watch_av(self):
if self.age < 18: if self.age < 18:
print('%s只能观看《熊出没》.' % self.name) print('%s只能观看《熊出没》.' % self.name)
else: else:
print('%s正在观看岛国爱情动作片.' % self.name) print('%s正在观看岛国爱情动作片.' % self.name)
def main(): def main():
stu1 = Student('骆昊', 38) stu1 = Student('骆昊', 38)
stu1.study('Python程序设计') stu1.study('Python程序设计')
stu1.watch_av() stu1.watch_av()
stu2 = Student('王大锤', 15) stu2 = Student('王大锤', 15)
stu2.study('思想品德') stu2.study('思想品德')
stu2.watch_av() stu2.watch_av()
if __name__ == '__main__': if __name__ == '__main__':
main() main()
\ No newline at end of file
""" """
对象之间的关联关系 对象之间的关联关系
Version: 0.1 Version: 0.1
Author: 骆昊 Author: 骆昊
Date: 2018-03-12 Date: 2018-03-12
""" """
from math import sqrt from math import sqrt
...@@ -13,61 +11,61 @@ from math import sqrt ...@@ -13,61 +11,61 @@ from math import sqrt
class Point(object): class Point(object):
def __init__(self, x=0, y=0): def __init__(self, x=0, y=0):
self._x = x self._x = x
self._y = y self._y = y
def move_to(self, x, y): def move_to(self, x, y):
self._x = x self._x = x
self._y = y self._y = y
def move_by(self, dx, dy): def move_by(self, dx, dy):
self._x += dx self._x += dx
self._y += dy self._y += dy
def distance_to(self, other): def distance_to(self, other):
dx = self._x - other._x dx = self._x - other._x
dy = self._y - other._y dy = self._y - other._y
return sqrt(dx ** 2 + dy ** 2) return sqrt(dx ** 2 + dy ** 2)
def __str__(self): def __str__(self):
return '(%s, %s)' % (str(self._x), str(self._y)) return '(%s, %s)' % (str(self._x), str(self._y))
class Line(object): class Line(object):
def __init__(self, start=Point(0, 0), end=Point(0, 0)): def __init__(self, start=Point(0, 0), end=Point(0, 0)):
self._start = start self._start = start
self._end = end self._end = end
@property @property
def start(self): def start(self):
return self._start return self._start
@start.setter @start.setter
def start(self, start): def start(self, start):
self._start = start self._start = start
@property @property
def end(self): def end(self):
return self.end return self.end
@end.setter @end.setter
def end(self, end): def end(self, end):
self._end = end self._end = end
@property @property
def length(self): def length(self):
return self._start.distance_to(self._end) return self._start.distance_to(self._end)
if __name__ == '__main__': if __name__ == '__main__':
p1 = Point(3, 5) p1 = Point(3, 5)
print(p1) print(p1)
p2 = Point(-2, -1.5) p2 = Point(-2, -1.5)
print(p2) print(p2)
line = Line(p1, p2) line = Line(p1, p2)
print(line.length) print(line.length)
line.start.move_to(2, 1) line.start.move_to(2, 1)
line.end = Point(1, 2) line.end = Point(1, 2)
print(line.length) print(line.length)
""" """
属性的使用 属性的使用
- 访问器/修改器/删除器 - 访问器/修改器/删除器
- 使用__slots__对属性加以限制 - 使用__slots__对属性加以限制
Version: 0.1 Version: 0.1
Author: 骆昊 Author: 骆昊
Date: 2018-03-12 Date: 2018-03-12
""" """
class Car(object): class Car(object):
__slots__ = ('_brand', '_max_speed') __slots__ = ('_brand', '_max_speed')
def __init__(self, brand, max_speed): def __init__(self, brand, max_speed):
self._brand = brand self._brand = brand
self._max_speed = max_speed self._max_speed = max_speed
@property @property
def brand(self): def brand(self):
return self._brand return self._brand
@brand.setter @brand.setter
def brand(self, brand): def brand(self, brand):
self._brand = brand self._brand = brand
@brand.deleter @brand.deleter
def brand(self): def brand(self):
del self._brand del self._brand
@property @property
def max_speed(self): def max_speed(self):
return self._max_speed return self._max_speed
@max_speed.setter @max_speed.setter
def max_speed(self, max_speed): def max_speed(self, max_speed):
if max_speed < 0: if max_speed < 0:
raise ValueError('Invalid max speed for car') raise ValueError('Invalid max speed for car')
self._max_speed = max_speed self._max_speed = max_speed
def __str__(self): def __str__(self):
return 'Car: [品牌=%s, 最高时速=%d]' % (self._brand, self._max_speed) return 'Car: [品牌=%s, 最高时速=%d]' % (self._brand, self._max_speed)
car = Car('QQ', 120) car = Car('QQ', 120)
......
""" """
属性的使用 属性的使用
- 使用已有方法定义访问器/修改器/删除器 - 使用已有方法定义访问器/修改器/删除器
Version: 0.1 Version: 0.1
Author: 骆昊 Author: 骆昊
Date: 2018-03-12 Date: 2018-03-12
""" """
class Car(object): class Car(object):
def __init__(self, brand, max_speed): def __init__(self, brand, max_speed):
self.set_brand(brand) self.set_brand(brand)
self.set_max_speed(max_speed) self.set_max_speed(max_speed)
def get_brand(self): def get_brand(self):
return self._brand return self._brand
def set_brand(self, brand): def set_brand(self, brand):
self._brand = brand self._brand = brand
def get_max_speed(self): def get_max_speed(self):
return self._max_speed return self._max_speed
def set_max_speed(self, max_speed): def set_max_speed(self, max_speed):
if max_speed < 0: if max_speed < 0:
raise ValueError('Invalid max speed for car') raise ValueError('Invalid max speed for car')
self._max_speed = max_speed self._max_speed = max_speed
def __str__(self): def __str__(self):
return 'Car: [品牌=%s, 最高时速=%d]' % (self._brand, self._max_speed) return 'Car: [品牌=%s, 最高时速=%d]' % (self._brand, self._max_speed)
# 用已有的修改器和访问器定义属性 # 用已有的修改器和访问器定义属性
brand = property(get_brand, set_brand) brand = property(get_brand, set_brand)
max_speed = property(get_max_speed, set_max_speed) max_speed = property(get_max_speed, set_max_speed)
car = Car('QQ', 120) car = Car('QQ', 120)
......
""" """
对象之间的依赖关系和运算符重载 对象之间的依赖关系和运算符重载
Version: 0.1 Version: 0.1
Author: 骆昊 Author: 骆昊
Date: 2018-03-12 Date: 2018-03-12
""" """
class Car(object): class Car(object):
def __init__(self, brand, max_speed): def __init__(self, brand, max_speed):
self._brand = brand self._brand = brand
self._max_speed = max_speed self._max_speed = max_speed
self._current_speed = 0 self._current_speed = 0
@property @property
def brand(self): def brand(self):
return self._brand return self._brand
def accelerate(self, delta): def accelerate(self, delta):
self._current_speed += delta self._current_speed += delta
if self._current_speed > self._max_speed: if self._current_speed > self._max_speed:
self._current_speed = self._max_speed self._current_speed = self._max_speed
def brake(self): def brake(self):
self._current_speed = 0 self._current_speed = 0
def __str__(self): def __str__(self):
return '%s当前时速%d' % (self._brand, self._current_speed) return '%s当前时速%d' % (self._brand, self._current_speed)
class Student(object): class Student(object):
def __init__(self, name, age): def __init__(self, name, age):
self._name = name self._name = name
self._age = age self._age = age
@property @property
def name(self): def name(self):
return self._name return self._name
# 学生和车之间存在依赖关系 - 学生使用了汽车 # 学生和车之间存在依赖关系 - 学生使用了汽车
def drive(self, car): def drive(self, car):
print('%s驾驶着%s欢快的行驶在去西天的路上' % (self._name, car._brand)) print('%s驾驶着%s欢快的行驶在去西天的路上' % (self._name, car._brand))
car.accelerate(30) car.accelerate(30)
print(car) print(car)
car.accelerate(50) car.accelerate(50)
print(car) print(car)
car.accelerate(50) car.accelerate(50)
print(car) print(car)
def study(self, course_name): def study(self, course_name):
print('%s正在学习%s.' % (self._name, course_name)) print('%s正在学习%s.' % (self._name, course_name))
def watch_av(self): def watch_av(self):
if self._age < 18: if self._age < 18:
print('%s只能观看《熊出没》.' % self._name) print('%s只能观看《熊出没》.' % self._name)
else: else:
print('%s正在观看岛国爱情动作片.' % self._name) print('%s正在观看岛国爱情动作片.' % self._name)
# 重载大于(>)运算符 # 重载大于(>)运算符
def __gt__(self, other): def __gt__(self, other):
return self._age > other._age return self._age > other._age
# 重载小于(<)运算符 # 重载小于(<)运算符
def __lt__(self, other): def __lt__(self, other):
return self._age < other._age return self._age < other._age
if __name__ == '__main__': if __name__ == '__main__':
stu1 = Student('骆昊', 38) stu1 = Student('骆昊', 38)
stu1.study('Python程序设计') stu1.study('Python程序设计')
stu1.watch_av() stu1.watch_av()
stu2 = Student('王大锤', 15) stu2 = Student('王大锤', 15)
stu2.study('思想品德') stu2.study('思想品德')
stu2.watch_av() stu2.watch_av()
car = Car('QQ', 120) car = Car('QQ', 120)
stu2.drive(car) stu2.drive(car)
print(stu1 > stu2) print(stu1 > stu2)
print(stu1 < stu2) print(stu1 < stu2)
""" """
多重继承 多重继承
- 菱形继承(钻石继承) - 菱形继承(钻石继承)
- C3算法(替代DFS的算法) - C3算法(替代DFS的算法)
Version: 0.1 Version: 0.1
Author: 骆昊 Author: 骆昊
Date: 2018-03-12 Date: 2018-03-12
""" """
class A(object): class A(object):
def foo(self): def foo(self):
print('foo of A') print('foo of A')
class B(A): class B(A):
pass pass
class C(A): class C(A):
def foo(self): def foo(self):
print('foo fo C') print('foo fo C')
class D(B, C): class D(B, C):
pass pass
class E(D): class E(D):
def foo(self): def foo(self):
print('foo in E') print('foo in E')
super().foo() super().foo()
super(B, self).foo() super(B, self).foo()
super(C, self).foo() super(C, self).foo()
if __name__ == '__main__': if __name__ == '__main__':
d = D() d = D()
d.foo() d.foo()
e = E() e = E()
e.foo() e.foo()
""" """
抽象类 / 方法重写 / 多态 抽象类 / 方法重写 / 多态
实现一个工资结算系统 公司有三种类型的员工 实现一个工资结算系统 公司有三种类型的员工
- 部门经理固定月薪12000元/月 - 部门经理固定月薪12000元/月
- 程序员按本月工作小时数每小时100元 - 程序员按本月工作小时数每小时100元
- 销售员1500元/月的底薪加上本月销售额5%的提成 - 销售员1500元/月的底薪加上本月销售额5%的提成
输入员工的信息 输出每位员工的月薪信息 输入员工的信息 输出每位员工的月薪信息
Version: 0.1 Version: 0.1
Author: 骆昊 Author: 骆昊
Date: 2018-03-12 Date: 2018-03-12
""" """
from abc import ABCMeta, abstractmethod from abc import ABCMeta, abstractmethod
...@@ -18,60 +16,60 @@ from abc import ABCMeta, abstractmethod ...@@ -18,60 +16,60 @@ from abc import ABCMeta, abstractmethod
class Employee(object, metaclass=ABCMeta): class Employee(object, metaclass=ABCMeta):
def __init__(self, name): def __init__(self, name):
self._name = name self._name = name
@property @property
def name(self): def name(self):
return self._name return self._name
@abstractmethod @abstractmethod
def get_salary(self): def get_salary(self):
pass pass
class Manager(Employee): class Manager(Employee):
# 想一想: 如果不定义构造方法会怎么样 # 想一想: 如果不定义构造方法会怎么样
def __init__(self, name): def __init__(self, name):
# 想一想: 如果不调用父类构造器会怎么样 # 想一想: 如果不调用父类构造器会怎么样
super().__init__(name) super().__init__(name)
def get_salary(self): def get_salary(self):
return 12000 return 12000
class Programmer(Employee): class Programmer(Employee):
def __init__(self, name): def __init__(self, name):
super().__init__(name) super().__init__(name)
def set_working_hour(self, working_hour): def set_working_hour(self, working_hour):
self._working_hour = working_hour self._working_hour = working_hour
def get_salary(self): def get_salary(self):
return 100 * self._working_hour return 100 * self._working_hour
class Salesman(Employee): class Salesman(Employee):
def __init__(self, name): def __init__(self, name):
super().__init__(name) super().__init__(name)
def set_sales(self, sales): def set_sales(self, sales):
self._sales = sales self._sales = sales
def get_salary(self): def get_salary(self):
return 1500 + self._sales * 0.05 return 1500 + self._sales * 0.05
if __name__ == '__main__': if __name__ == '__main__':
emps = [Manager('武则天'), Programmer('狄仁杰'), Salesman('白元芳')] emps = [Manager('武则天'), Programmer('狄仁杰'), Salesman('白元芳')]
for emp in emps: for emp in emps:
if isinstance(emp, Programmer): if isinstance(emp, Programmer):
working_hour = int(input('请输入%s本月工作时间: ' % emp.name)) working_hour = int(input('请输入%s本月工作时间: ' % emp.name))
emp.set_working_hour(working_hour) emp.set_working_hour(working_hour)
elif isinstance(emp, Salesman): elif isinstance(emp, Salesman):
sales = float(input('请输入%s本月销售额: ' % emp.name)) sales = float(input('请输入%s本月销售额: ' % emp.name))
emp.set_sales(sales) emp.set_sales(sales)
print('%s本月月薪为: ¥%.2f元' % (emp.name, emp.get_salary())) print('%s本月月薪为: ¥%.2f元' % (emp.name, emp.get_salary()))
""" """
多重继承 多重继承
- 通过多重继承可以给一个类的对象具备多方面的能力 - 通过多重继承可以给一个类的对象具备多方面的能力
- 这样在设计类的时候可以避免设计太多层次的复杂的继承关系 - 这样在设计类的时候可以避免设计太多层次的复杂的继承关系
Version: 0.1 Version: 0.1
Author: 骆昊 Author: 骆昊
Date: 2018-03-12 Date: 2018-03-12
""" """
class Father(object): class Father(object):
def __init__(self, name): def __init__(self, name):
self._name = name self._name = name
def gamble(self): def gamble(self):
print('%s在打麻将.' % self._name) print('%s在打麻将.' % self._name)
def eat(self): def eat(self):
print('%s在大吃大喝.' % self._name) print('%s在大吃大喝.' % self._name)
class Monk(object): class Monk(object):
def __init__(self, name): def __init__(self, name):
self._name = name self._name = name
def eat(self): def eat(self):
print('%s在吃斋.' % self._name) print('%s在吃斋.' % self._name)
def chant(self): def chant(self):
print('%s在念经.' % self._name) print('%s在念经.' % self._name)
class Musician(object): class Musician(object):
def __init__(self, name): def __init__(self, name):
self._name = name self._name = name
def eat(self): def eat(self):
print('%s在细嚼慢咽.' % self._name) print('%s在细嚼慢咽.' % self._name)
def play_piano(self): def play_piano(self):
print('%s在弹钢琴.' % self._name) print('%s在弹钢琴.' % self._name)
# 试一试下面的代码看看有什么区别 # 试一试下面的代码看看有什么区别
...@@ -54,10 +52,10 @@ class Musician(object): ...@@ -54,10 +52,10 @@ class Musician(object):
class Son(Father, Monk, Musician): class Son(Father, Monk, Musician):
def __init__(self, name): def __init__(self, name):
Father.__init__(self, name) Father.__init__(self, name)
Monk.__init__(self, name) Monk.__init__(self, name)
Musician.__init__(self, name) Musician.__init__(self, name)
son = Son('王大锤') son = Son('王大锤')
......
""" """
运算符重载 - 自定义分数类 运算符重载 - 自定义分数类
Version: 0.1 Version: 0.1
Author: 骆昊 Author: 骆昊
Date: 2018-03-12 Date: 2018-03-12
""" """
from math import gcd from math import gcd
...@@ -13,64 +11,64 @@ from math import gcd ...@@ -13,64 +11,64 @@ from math import gcd
class Rational(object): class Rational(object):
def __init__(self, num, den=1): def __init__(self, num, den=1):
if den == 0: if den == 0:
raise ValueError('分母不能为0') raise ValueError('分母不能为0')
self._num = num self._num = num
self._den = den self._den = den
self.normalize() self.normalize()
def simplify(self): def simplify(self):
x = abs(self._num) x = abs(self._num)
y = abs(self._den) y = abs(self._den)
factor = gcd(x, y) factor = gcd(x, y)
if factor > 1: if factor > 1:
self._num //= factor self._num //= factor
self._den //= factor self._den //= factor
return self return self
def normalize(self): def normalize(self):
if self._den < 0: if self._den < 0:
self._den = -self._den self._den = -self._den
self._num = -self._num self._num = -self._num
return self return self
def __add__(self, other): def __add__(self, other):
new_num = self._num * other._den + other._num * self._den new_num = self._num * other._den + other._num * self._den
new_den = self._den * other._den new_den = self._den * other._den
return Rational(new_num, new_den).simplify().normalize() return Rational(new_num, new_den).simplify().normalize()
def __sub__(self, other): def __sub__(self, other):
new_num = self._num * other._den - other._num * self._den new_num = self._num * other._den - other._num * self._den
new_den = self._den * other._den new_den = self._den * other._den
return Rational(new_num, new_den).simplify().normalize() return Rational(new_num, new_den).simplify().normalize()
def __mul__(self, other): def __mul__(self, other):
new_num = self._num * other._num new_num = self._num * other._num
new_den = self._den * other._den new_den = self._den * other._den
return Rational(new_num, new_den).simplify().normalize() return Rational(new_num, new_den).simplify().normalize()
def __truediv__(self, other): def __truediv__(self, other):
new_num = self._num * other._den new_num = self._num * other._den
new_den = self._den * other._num new_den = self._den * other._num
return Rational(new_num, new_den).simplify().normalize() return Rational(new_num, new_den).simplify().normalize()
def __str__(self): def __str__(self):
if self._num == 0: if self._num == 0:
return '0' return '0'
elif self._den == 1: elif self._den == 1:
return str(self._num) return str(self._num)
else: else:
return '(%d/%d)' % (self._num, self._den) return '(%d/%d)' % (self._num, self._den)
if __name__ == '__main__': if __name__ == '__main__':
r1 = Rational(2, 3) r1 = Rational(2, 3)
print(r1) print(r1)
r2 = Rational(6, -8) r2 = Rational(6, -8)
print(r2) print(r2)
print(r2.simplify()) print(r2.simplify())
print('%s + %s = %s' % (r1, r2, r1 + r2)) print('%s + %s = %s' % (r1, r2, r1 + r2))
print('%s - %s = %s' % (r1, r2, r1 - r2)) print('%s - %s = %s' % (r1, r2, r1 - r2))
print('%s * %s = %s' % (r1, r2, r1 * r2)) print('%s * %s = %s' % (r1, r2, r1 * r2))
print('%s / %s = %s' % (r1, r2, r1 / r2)) print('%s / %s = %s' % (r1, r2, r1 / r2))
""" """
继承的应用 继承的应用
- 抽象类 - 抽象类
- 抽象方法 - 抽象方法
- 方法重写 - 方法重写
- 多态 - 多态
Version: 0.1 Version: 0.1
Author: 骆昊 Author: 骆昊
Date: 2018-03-12 Date: 2018-03-12
""" """
from abc import ABCMeta, abstractmethod from abc import ABCMeta, abstractmethod
...@@ -18,49 +16,49 @@ from math import pi ...@@ -18,49 +16,49 @@ from math import pi
class Shape(object, metaclass=ABCMeta): class Shape(object, metaclass=ABCMeta):
@abstractmethod @abstractmethod
def perimeter(self): def perimeter(self):
pass pass
@abstractmethod @abstractmethod
def area(self): def area(self):
pass pass
class Circle(Shape): class Circle(Shape):
def __init__(self, radius): def __init__(self, radius):
self._radius = radius self._radius = radius
def perimeter(self): def perimeter(self):
return 2 * pi * self._radius return 2 * pi * self._radius
def area(self): def area(self):
return pi * self._radius ** 2 return pi * self._radius ** 2
def __str__(self): def __str__(self):
return '我是一个圆' return '我是一个圆'
class Rect(Shape): class Rect(Shape):
def __init__(self, width, height): def __init__(self, width, height):
self._width = width self._width = width
self._height = height self._height = height
def perimeter(self): def perimeter(self):
return 2 * (self._width + self._height) return 2 * (self._width + self._height)
def area(self): def area(self):
return self._width * self._height return self._width * self._height
def __str__(self): def __str__(self):
return '我是一个矩形' return '我是一个矩形'
if __name__ == '__main__': if __name__ == '__main__':
shapes = [Circle(5), Circle(3.2), Rect(3.2, 6.3)] shapes = [Circle(5), Circle(3.2), Rect(3.2, 6.3)]
for shape in shapes: for shape in shapes:
print(shape) print(shape)
print('周长:', shape.perimeter()) print('周长:', shape.perimeter())
print('面积:', shape.area()) print('面积:', shape.area())
""" """
实例方法和类方法的应用 实例方法和类方法的应用
Version: 0.1 Version: 0.1
Author: 骆昊 Author: 骆昊
Date: 2018-03-12 Date: 2018-03-12
""" """
from math import sqrt from math import sqrt
...@@ -13,41 +11,41 @@ from math import sqrt ...@@ -13,41 +11,41 @@ from math import sqrt
class Triangle(object): class Triangle(object):
def __init__(self, a, b, c): def __init__(self, a, b, c):
self._a = a self._a = a
self._b = b self._b = b
self._c = c self._c = c
# 静态方法 # 静态方法
@staticmethod @staticmethod
def is_valid(a, b, c): def is_valid(a, b, c):
return a + b > c and b + c > a and c + a > b return a + b > c and b + c > a and c + a > b
# 实例方法 # 实例方法
def perimeter(self): def perimeter(self):
return self._a + self._b + self._c return self._a + self._b + self._c
# 实例方法 # 实例方法
def area(self): def area(self):
p = self.perimeter() / 2 p = self.perimeter() / 2
return sqrt(p * (p - self._a) * (p - self._b) * (p - self._c)) return sqrt(p * (p - self._a) * (p - self._b) * (p - self._c))
if __name__ == '__main__': if __name__ == '__main__':
# 用字符串的split方法将字符串拆分成一个列表 # 用字符串的split方法将字符串拆分成一个列表
# 再通过map函数对列表中的每个字符串进行映射处理成小数 # 再通过map函数对列表中的每个字符串进行映射处理成小数
a, b, c = map(float, input('请输入三条边: ').split()) a, b, c = map(float, input('请输入三条边: ').split())
# 先判断给定长度的三条边能否构成三角形 # 先判断给定长度的三条边能否构成三角形
# 如果能才创建三角形对象 # 如果能才创建三角形对象
if Triangle.is_valid(a, b, c): if Triangle.is_valid(a, b, c):
tri = Triangle(a, b, c) tri = Triangle(a, b, c)
print('周长:', tri.perimeter()) print('周长:', tri.perimeter())
print('面积:', tri.area()) print('面积:', tri.area())
# 如果传入对象作为方法参数也可以通过类调用实例方法 # 如果传入对象作为方法参数也可以通过类调用实例方法
# print('周长:', Triangle.perimeter(tri)) # print('周长:', Triangle.perimeter(tri))
# print('面积:', Triangle.area(tri)) # print('面积:', Triangle.area(tri))
# 看看下面的代码就知道其实二者本质上是一致的 # 看看下面的代码就知道其实二者本质上是一致的
# print(type(tri.perimeter)) # print(type(tri.perimeter))
# print(type(Triangle.perimeter)) # print(type(Triangle.perimeter))
else: else:
print('不能构成三角形.') print('不能构成三角形.')
""" """
使用tkinter创建GUI 使用tkinter创建GUI
- 顶层窗口 - 顶层窗口
- 控件 - 控件
- 布局 - 布局
- 事件回调 - 事件回调
Version: 0.1 Version: 0.1
Author: 骆昊 Author: 骆昊
Date: 2018-03-14 Date: 2018-03-14
""" """
import tkinter import tkinter
...@@ -17,41 +15,41 @@ import tkinter.messagebox ...@@ -17,41 +15,41 @@ import tkinter.messagebox
def main(): def main():
flag = True flag = True
# 修改标签上的文字 # 修改标签上的文字
def change_label_text(): def change_label_text():
nonlocal flag nonlocal flag
flag = not flag flag = not flag
color, msg = ('red', 'Hello, world!')\ color, msg = ('red', 'Hello, world!')\
if flag else ('blue', 'Goodbye, world!') if flag else ('blue', 'Goodbye, world!')
label.config(text=msg, fg=color) label.config(text=msg, fg=color)
# 确认退出 # 确认退出
def confirm_to_quit(): def confirm_to_quit():
if tkinter.messagebox.askokcancel('温馨提示', '确定要退出吗?'): if tkinter.messagebox.askokcancel('温馨提示', '确定要退出吗?'):
top.quit() top.quit()
# 创建顶层窗口 # 创建顶层窗口
top = tkinter.Tk() top = tkinter.Tk()
# 设置窗口大小 # 设置窗口大小
top.geometry('240x160') top.geometry('240x160')
# 设置窗口标题 # 设置窗口标题
top.title('小游戏') top.title('小游戏')
# 创建标签对象 # 创建标签对象
label = tkinter.Label(top, text='Hello, world!', font='Arial -32', fg='red') label = tkinter.Label(top, text='Hello, world!', font='Arial -32', fg='red')
label.pack(expand=1) label.pack(expand=1)
# 创建一个装按钮的容器 # 创建一个装按钮的容器
panel = tkinter.Frame(top) panel = tkinter.Frame(top)
# 创建按钮对象 # 创建按钮对象
button1 = tkinter.Button(panel, text='修改', command=change_label_text) button1 = tkinter.Button(panel, text='修改', command=change_label_text)
button1.pack(side='left') button1.pack(side='left')
button2 = tkinter.Button(panel, text='退出', command=confirm_to_quit) button2 = tkinter.Button(panel, text='退出', command=confirm_to_quit)
button2.pack(side='right') button2.pack(side='right')
panel.pack(side='bottom') panel.pack(side='bottom')
# 开启主事件循环 # 开启主事件循环
tkinter.mainloop() tkinter.mainloop()
if __name__ == '__main__': if __name__ == '__main__':
main() main()
""" """
使用tkinter创建GUI 使用tkinter创建GUI
- 使用画布绘图 - 使用画布绘图
- 处理鼠标事件 - 处理鼠标事件
Version: 0.1 Version: 0.1
Author: 骆昊 Author: 骆昊
Date: 2018-03-14 Date: 2018-03-14
""" """
import tkinter import tkinter
def mouse_evt_handler(evt=None): def mouse_evt_handler(evt=None):
row = round((evt.y - 20) / 40) row = round((evt.y - 20) / 40)
col = round((evt.x - 20) / 40) col = round((evt.x - 20) / 40)
pos_x = 40 * col pos_x = 40 * col
pos_y = 40 * row pos_y = 40 * row
canvas.create_oval(pos_x, pos_y, 40 + pos_x, 40 + pos_y, fill='black') canvas.create_oval(pos_x, pos_y, 40 + pos_x, 40 + pos_y, fill='black')
top = tkinter.Tk() top = tkinter.Tk()
...@@ -34,8 +32,8 @@ canvas = tkinter.Canvas(top, width=600, height=600, bd=0, highlightthickness=0) ...@@ -34,8 +32,8 @@ canvas = tkinter.Canvas(top, width=600, height=600, bd=0, highlightthickness=0)
canvas.bind('<Button-1>', mouse_evt_handler) canvas.bind('<Button-1>', mouse_evt_handler)
canvas.create_rectangle(0, 0, 600, 600, fill='yellow', outline='white') canvas.create_rectangle(0, 0, 600, 600, fill='yellow', outline='white')
for index in range(15): for index in range(15):
canvas.create_line(20, 20 + 40 * index, 580, 20 + 40 * index, fill='black') canvas.create_line(20, 20 + 40 * index, 580, 20 + 40 * index, fill='black')
canvas.create_line(20 + 40 * index, 20, 20 + 40 * index, 580, fill='black') canvas.create_line(20 + 40 * index, 20, 20 + 40 * index, 580, fill='black')
canvas.create_rectangle(15, 15, 585, 585, outline='black', width=4) canvas.create_rectangle(15, 15, 585, 585, outline='black', width=4)
canvas.pack() canvas.pack()
tkinter.mainloop() tkinter.mainloop()
......
""" """
使用tkinter创建GUI 使用tkinter创建GUI
- 在窗口上制作动画 - 在窗口上制作动画
Version: 0.1 Version: 0.1
Author: 骆昊 Author: 骆昊
...@@ -15,9 +15,9 @@ import time ...@@ -15,9 +15,9 @@ import time
# 播放动画效果的函数 # 播放动画效果的函数
def play_animation(): def play_animation():
canvas.move(oval, 2, 2) canvas.move(oval, 2, 2)
canvas.update() canvas.update()
top.after(50, play_animation) top.after(50, play_animation)
x = 10 x = 10
......
...@@ -19,7 +19,7 @@ turtle.fillcolor('yellow') ...@@ -19,7 +19,7 @@ turtle.fillcolor('yellow')
turtle.pendown() turtle.pendown()
turtle.begin_fill() turtle.begin_fill()
for _ in range(36): for _ in range(36):
turtle.forward(200) turtle.forward(200)
turtle.right(170) turtle.right(170)
turtle.end_fill() turtle.end_fill()
turtle.mainloop() turtle.mainloop()
""" """
读取CSV文件 读取CSV文件
Version: 0.1 Version: 0.1
Author: 骆昊 Author: 骆昊
Date: 2018-03-13 Date: 2018-03-13
""" """
import csv import csv
...@@ -13,11 +11,11 @@ import csv ...@@ -13,11 +11,11 @@ import csv
filename = 'example.csv' filename = 'example.csv'
try: try:
with open(filename) as f: with open(filename) as f:
reader = csv.reader(f) reader = csv.reader(f)
data = list(reader) data = list(reader)
except FileNotFoundError: except FileNotFoundError:
print('无法打开文件:', filename) print('无法打开文件:', filename)
else: else:
for item in data: for item in data:
print('%-30s%-20s%-10s' % (item[0], item[1], item[2])) print('%-30s%-20s%-10s' % (item[0], item[1], item[2]))
""" """
写入CSV文件 写入CSV文件
Version: 0.1 Version: 0.1
Author: 骆昊 Author: 骆昊
Date: 2018-03-13 Date: 2018-03-13
""" """
import csv import csv
...@@ -13,34 +11,34 @@ import csv ...@@ -13,34 +11,34 @@ import csv
class Teacher(object): class Teacher(object):
def __init__(self, name, age, title): def __init__(self, name, age, title):
self.__name = name self.__name = name
self.__age = age self.__age = age
self.__title = title self.__title = title
self.__index = -1 self.__index = -1
@property @property
def name(self): def name(self):
return self.__name return self.__name
@property @property
def age(self): def age(self):
return self.__age return self.__age
@property @property
def title(self): def title(self):
return self.__title return self.__title
filename = 'teacher.csv' filename = 'teacher.csv'
teachers = [Teacher('骆昊', 38, '叫兽'), Teacher('狄仁杰', 25, '砖家')] teachers = [Teacher('骆昊', 38, '叫兽'), Teacher('狄仁杰', 25, '砖家')]
try: try:
with open(filename, 'w') as f: with open(filename, 'w') as f:
writer = csv.writer(f) writer = csv.writer(f)
for teacher in teachers: for teacher in teachers:
writer.writerow([teacher.name, teacher.age, teacher.title]) writer.writerow([teacher.name, teacher.age, teacher.title])
except BaseException as e: except BaseException as e:
print('无法写入文件:', filename) print('无法写入文件:', filename)
else: else:
print('保存数据完成!') print('保存数据完成!')
""" """
异常机制 - 处理程序在运行时可能发生的状态 异常机制 - 处理程序在运行时可能发生的状态
Version: 0.1 Version: 0.1
Author: 骆昊 Author: 骆昊
Date: 2018-03-13 Date: 2018-03-13
""" """
input_again = True input_again = True
while input_again: while input_again:
try: try:
a = int(input('a = ')) a = int(input('a = '))
b = int(input('b = ')) b = int(input('b = '))
print('%d / %d = %f' % (a, b, a / b)) print('%d / %d = %f' % (a, b, a / b))
input_again = False input_again = False
except ValueError: except ValueError:
print('请输入整数') print('请输入整数')
except ZeroDivisionError: except ZeroDivisionError:
print('除数不能为0') print('除数不能为0')
# 处理异常让代码不因异常而崩溃是一方面 # 处理异常让代码不因异常而崩溃是一方面
# 更重要的是可以通过对异常的处理让代码从异常中恢复过来 # 更重要的是可以通过对异常的处理让代码从异常中恢复过来
""" """
异常机制 - 处理程序在运行时可能发生的状态 异常机制 - 处理程序在运行时可能发生的状态
Version: 0.1 Version: 0.1
Author: 骆昊 Author: 骆昊
Date: 2018-03-13 Date: 2018-03-13
""" """
input_again = True input_again = True
while input_again: while input_again:
try: try:
a = int(input('a = ')) a = int(input('a = '))
b = int(input('b = ')) b = int(input('b = '))
print('%d / %d = %f' % (a, b, a / b)) print('%d / %d = %f' % (a, b, a / b))
input_again = False input_again = False
except (ValueError, ZeroDivisionError) as msg: except (ValueError, ZeroDivisionError) as msg:
print(msg) print(msg)
""" """
异常机制 - 处理程序在运行时可能发生的状态 异常机制 - 处理程序在运行时可能发生的状态
Version: 0.1 Version: 0.1
Author: 骆昊 Author: 骆昊
Date: 2018-03-13 Date: 2018-03-13
""" """
import time import time
...@@ -13,18 +11,18 @@ import sys ...@@ -13,18 +11,18 @@ import sys
filename = input('请输入文件名: ') filename = input('请输入文件名: ')
try: try:
with open(filename) as f: with open(filename) as f:
lines = f.readlines() lines = f.readlines()
except FileNotFoundError as msg: except FileNotFoundError as msg:
print('无法打开文件:', filename) print('无法打开文件:', filename)
print(msg) print(msg)
except UnicodeDecodeError as msg: except UnicodeDecodeError as msg:
print('非文本文件无法解码') print('非文本文件无法解码')
sys.exit() sys.exit()
else: else:
for line in lines: for line in lines:
print(line.rstrip()) print(line.rstrip())
time.sleep(0.5) time.sleep(0.5)
finally: finally:
# 此处最适合做善后工作 # 此处最适合做善后工作
print('不管发生什么我都会执行') print('不管发生什么我都会执行')
""" """
引发异常和异常栈 引发异常和异常栈
Version: 0.1 Version: 0.1
Author: 骆昊 Author: 骆昊
Date: 2018-03-13 Date: 2018-03-13
""" """
def f1(): def f1():
raise AssertionError('发生异常') raise AssertionError('发生异常')
def f2(): def f2():
f1() f1()
def f3(): def f3():
f2() f2()
f3() f3()
""" """
从文本文件中读取数据 从文本文件中读取数据
Version: 0.1 Version: 0.1
Author: 骆昊 Author: 骆昊
Date: 2018-03-13 Date: 2018-03-13
""" """
import time import time
def main(): def main():
# 一次性读取整个文件内容 # 一次性读取整个文件内容
with open('致橡树.txt', 'r', encoding='utf-8') as f: with open('致橡树.txt', 'r', encoding='utf-8') as f:
print(f.read()) print(f.read())
# 通过for-in循环逐行读取 # 通过for-in循环逐行读取
with open('致橡树.txt', mode='r') as f: with open('致橡树.txt', mode='r') as f:
for line in f: for line in f:
print(line, end='') print(line, end='')
time.sleep(0.5) time.sleep(0.5)
print() print()
# 读取文件按行读取到列表中 # 读取文件按行读取到列表中
with open('致橡树.txt') as f: with open('致橡树.txt') as f:
lines = f.readlines() lines = f.readlines()
print(lines) print(lines)
if __name__ == '__main__': if __name__ == '__main__':
main() main()
""" """
读取圆周率文件判断其中是否包含自己的生日 读取圆周率文件判断其中是否包含自己的生日
Version: 0.1 Version: 0.1
Author: 骆昊 Author: 骆昊
Date: 2018-03-13 Date: 2018-03-13
""" """
birth = input('请输入你的生日: ') birth = input('请输入你的生日: ')
with open('pi_million_digits.txt') as f: with open('pi_million_digits.txt') as f:
lines = f.readlines() lines = f.readlines()
pi_string = '' pi_string = ''
for line in lines: for line in lines:
pi_string += line.strip() pi_string += line.strip()
if birth in pi_string: if birth in pi_string:
print('Bingo!!!') print('Bingo!!!')
""" """
写文本文件 写文本文件
将100以内的素数写入到文件中 将100以内的素数写入到文件中
Version: 0.1 Version: 0.1
Author: 骆昊 Author: 骆昊
Date: 2018-03-13 Date: 2018-03-13
""" """
from math import sqrt from math import sqrt
def is_prime(n): def is_prime(n):
for factor in range(2, int(sqrt(n)) + 1): for factor in range(2, int(sqrt(n)) + 1):
if n % factor == 0: if n % factor == 0:
return False return False
return True return True
# 试一试有什么不一样 # 试一试有什么不一样
# with open('prime.txt', 'a') as f: # with open('prime.txt', 'a') as f:
with open('prime.txt', 'w') as f: with open('prime.txt', 'w') as f:
for num in range(2, 100): for num in range(2, 100):
if is_prime(num): if is_prime(num):
f.write(str(num) + '\n') f.write(str(num) + '\n')
print('写入完成!') print('写入完成!')
""" """
读写二进制文件 读写二进制文件
Version: 0.1 Version: 0.1
Author: 骆昊 Author: 骆昊
Date: 2018-03-13 Date: 2018-03-13
""" """
import base64 import base64
with open('mm.jpg', 'rb') as f: with open('mm.jpg', 'rb') as f:
data = f.read() data = f.read()
# print(type(data)) # print(type(data))
# print(data) # print(data)
print('字节数:', len(data)) print('字节数:', len(data))
# 将图片处理成BASE-64编码 # 将图片处理成BASE-64编码
print(base64.b64encode(data)) print(base64.b64encode(data))
with open('girl.jpg', 'wb') as f: with open('girl.jpg', 'wb') as f:
f.write(data) f.write(data)
print('写入完成!') print('写入完成!')
""" """
读取JSON数据 读取JSON数据
Version: 0.1 Version: 0.1
Author: 骆昊 Author: 骆昊
Date: 2018-03-13 Date: 2018-03-13
""" """
import json import json
...@@ -28,60 +26,60 @@ print(teacher.title) ...@@ -28,60 +26,60 @@ print(teacher.title)
# 请思考如何将下面JSON格式的天气数据转换成对象并获取我们需要的信息 # 请思考如何将下面JSON格式的天气数据转换成对象并获取我们需要的信息
# 稍后我们会讲解如何通过网络API获取我们需要的JSON格式的数据 # 稍后我们会讲解如何通过网络API获取我们需要的JSON格式的数据
""" """
{ {
"wendu": "29", "wendu": "29",
"ganmao": "各项气象条件适宜,发生感冒机率较低。但请避免长期处于空调房间中,以防感冒。", "ganmao": "各项气象条件适宜,发生感冒机率较低。但请避免长期处于空调房间中,以防感冒。",
"forecast": [ "forecast": [
{ {
"fengxiang": "南风", "fengxiang": "南风",
"fengli": "3-4级", "fengli": "3-4级",
"high": "高温 32℃", "high": "高温 32℃",
"type": "多云", "type": "多云",
"low": "低温 17℃", "low": "低温 17℃",
"date": "16日星期二" "date": "16日星期二"
}, },
{ {
"fengxiang": "南风", "fengxiang": "南风",
"fengli": "微风级", "fengli": "微风级",
"high": "高温 34℃", "high": "高温 34℃",
"type": "晴", "type": "晴",
"low": "低温 19℃", "low": "低温 19℃",
"date": "17日星期三" "date": "17日星期三"
}, },
{ {
"fengxiang": "南风", "fengxiang": "南风",
"fengli": "微风级", "fengli": "微风级",
"high": "高温 35℃", "high": "高温 35℃",
"type": "晴", "type": "晴",
"low": "低温 22℃", "low": "低温 22℃",
"date": "18日星期四" "date": "18日星期四"
}, },
{ {
"fengxiang": "南风", "fengxiang": "南风",
"fengli": "微风级", "fengli": "微风级",
"high": "高温 35℃", "high": "高温 35℃",
"type": "多云", "type": "多云",
"low": "低温 22℃", "low": "低温 22℃",
"date": "19日星期五" "date": "19日星期五"
}, },
{ {
"fengxiang": "南风", "fengxiang": "南风",
"fengli": "3-4级", "fengli": "3-4级",
"high": "高温 34℃", "high": "高温 34℃",
"type": "晴", "type": "晴",
"low": "低温 21℃", "low": "低温 21℃",
"date": "20日星期六" "date": "20日星期六"
} }
], ],
"yesterday": { "yesterday": {
"fl": "微风", "fl": "微风",
"fx": "南风", "fx": "南风",
"high": "高温 28℃", "high": "高温 28℃",
"type": "晴", "type": "晴",
"low": "低温 15℃", "low": "低温 15℃",
"date": "15日星期一" "date": "15日星期一"
}, },
"aqi": "72", "aqi": "72",
"city": "北京" "city": "北京"
} }
""" """
""" """
写入JSON文件 写入JSON文件
Version: 0.1 Version: 0.1
Author: 骆昊 Author: 骆昊
Date: 2018-03-13 Date: 2018-03-13
""" """
import json import json
......
...@@ -5,3 +5,28 @@ ...@@ -5,3 +5,28 @@
我如果爱你 我如果爱你
绝不学痴情的鸟儿 绝不学痴情的鸟儿
为绿荫重复单调的歌曲 为绿荫重复单调的歌曲
也不止像泉源
常年送来清凉的慰藉
也不止像险峰
增加你的高度 衬托你的威仪
甚至日光 甚至春雨
不 这些都还不够
我必须是你近旁的一株木棉
作为树的形象和你站在一起
根 紧握在地下
叶 相触在云里
每一阵风过
我们都互相致意
但没有人 听懂我们的言语
你有你的铜枝铁干
像刀 像剑 也像戟;
我有我红硕的花朵
像沉重的叹息 又像英勇的火炬
我们分担寒潮、风雷、霹雳
我们共享雾霭、流岚、虹霓
仿佛永远分离 却又终身相依
这才是伟大的爱情
坚贞就在这里
爱 不仅爱你伟岸的身躯
也爱你坚持的位置 足下的土地
\ No newline at end of file
""" """
字符串常用操作 字符串常用操作
Version: 0.1 Version: 0.1
Author: 骆昊 Author: 骆昊
Date: 2018-03-19 Date: 2018-03-19
""" """
import pyperclip import pyperclip
......
""" """
字符串常用操作 - 实现字符串倒转的方法 字符串常用操作 - 实现字符串倒转的方法
Version: 0.1 Version: 0.1
Author: 骆昊 Author: 骆昊
Date: 2018-03-19 Date: 2018-03-19
""" """
from io import StringIO from io import StringIO
def reverse_str1(str): def reverse_str1(str):
return str[::-1] return str[::-1]
def reverse_str2(str): def reverse_str2(str):
if len(str) <= 1: if len(str) <= 1:
return str return str
return reverse_str2(str[1:]) + str[0:1] return reverse_str2(str[1:]) + str[0:1]
def reverse_str3(str): def reverse_str3(str):
# StringIO对象是Python中的可变字符串 # StringIO对象是Python中的可变字符串
# 不应该使用不变字符串做字符串连接操作 因为会产生很多无用字符串对象 # 不应该使用不变字符串做字符串连接操作 因为会产生很多无用字符串对象
rstr = StringIO() rstr = StringIO()
str_len = len(str) str_len = len(str)
for index in range(str_len - 1, -1, -1): for index in range(str_len - 1, -1, -1):
rstr.write(str[index]) rstr.write(str[index])
return rstr.getvalue() return rstr.getvalue()
def reverse_str4(str): def reverse_str4(str):
return ''.join(str[index] for index in range(len(str) - 1, -1, -1)) return ''.join(str[index] for index in range(len(str) - 1, -1, -1))
def reverse_str5(str): def reverse_str5(str):
# 将字符串处理成列表 # 将字符串处理成列表
str_list = list(str) str_list = list(str)
str_len = len(str) str_len = len(str)
# 使用zip函数将两个序列合并成一个产生元组的迭代器 # 使用zip函数将两个序列合并成一个产生元组的迭代器
# 每次正好可以取到一前一后两个下标来实现元素的交换 # 每次正好可以取到一前一后两个下标来实现元素的交换
for i, j in zip(range(str_len // 2), range(str_len - 1, str_len // 2, -1)): for i, j in zip(range(str_len // 2), range(str_len - 1, str_len // 2, -1)):
str_list[i], str_list[j] = str_list[j], str_list[i] str_list[i], str_list[j] = str_list[j], str_list[i]
# 将列表元素连接成字符串 # 将列表元素连接成字符串
return ''.join(str_list) return ''.join(str_list)
if __name__ == '__main__': if __name__ == '__main__':
str = 'I love Python' str = 'I love Python'
print(reverse_str1(str)) print(reverse_str1(str))
print(str) print(str)
print(reverse_str2(str)) print(reverse_str2(str))
print(str) print(str)
print(reverse_str3(str)) print(reverse_str3(str))
print(str) print(str)
print(reverse_str4(str)) print(reverse_str4(str))
print(str) print(str)
print(reverse_str5(str)) print(reverse_str5(str))
print(str) print(str)
# 提醒学生注意这是一个面试题: 写出你能想到的实现字符串倒转的代码
""" """
验证输入用户名和QQ号是否有效并给出对应的提示信息 验证输入用户名和QQ号是否有效并给出对应的提示信息
要求: 要求:
用户名必须由字母、数字或下划线构成且长度在6~20个字符之间 用户名必须由字母、数字或下划线构成且长度在6~20个字符之间
QQ号是5~12的数字且首位不能为0 QQ号是5~12的数字且首位不能为0
""" """
import re import re
...@@ -26,4 +24,3 @@ def main(): ...@@ -26,4 +24,3 @@ def main():
if __name__ == '__main__': if __name__ == '__main__':
main() main()
"""
不良内容过滤
"""
import re import re
def main(): def main():
sentence = '你丫是傻叉吗? 我操你大爷的. Fuck you.' sentence = '你丫是傻叉吗? 我操你大爷的. Fuck you.'
purified = re.sub('[操肏艹草曹]|fuck|shit|傻[比屄逼叉缺吊屌]|煞笔', purified = re.sub('[操肏艹]|fuck|shit|傻[比屄逼叉缺吊屌]|煞笔',
'*', sentence, flags=re.IGNORECASE) '*', sentence, flags=re.IGNORECASE)
print(purified) print(purified)
......
""" """
异步I/O操作 - asyncio模块 异步I/O操作 - asyncio模块
Version: 0.1 Version: 0.1
Author: 骆昊 Author: 骆昊
Date: 2018-03-21 Date: 2018-03-21
""" """
import asyncio import asyncio
...@@ -15,13 +13,13 @@ import threading ...@@ -15,13 +13,13 @@ import threading
@asyncio.coroutine @asyncio.coroutine
def hello(): def hello():
print('%s: hello, world!' % threading.current_thread()) print('%s: hello, world!' % threading.current_thread())
# 休眠不会阻塞主线程因为使用了异步I/O操作 # 休眠不会阻塞主线程因为使用了异步I/O操作
# 注意有yield from才会等待休眠操作执行完成 # 注意有yield from才会等待休眠操作执行完成
yield from asyncio.sleep(2) yield from asyncio.sleep(2)
# asyncio.sleep(1) # asyncio.sleep(1)
# time.sleep(1) # time.sleep(1)
print('%s: goodbye, world!' % threading.current_thread()) print('%s: goodbye, world!' % threading.current_thread())
loop = asyncio.get_event_loop() loop = asyncio.get_event_loop()
......
""" """
异步I/O操作 - async和await 异步I/O操作 - async和await
Version: 0.1 Version: 0.1
Author: 骆昊 Author: 骆昊
Date: 2018-03-21 Date: 2018-03-21
""" """
import asyncio import asyncio
import threading import threading
...@@ -15,9 +12,9 @@ import threading ...@@ -15,9 +12,9 @@ import threading
# 通过async修饰的函数不再是普通函数而是一个协程 # 通过async修饰的函数不再是普通函数而是一个协程
# 注意async和await将在Python 3.7中作为关键字出现 # 注意async和await将在Python 3.7中作为关键字出现
async def hello(): async def hello():
print('%s: hello, world!' % threading.current_thread()) print('%s: hello, world!' % threading.current_thread())
await asyncio.sleep(2) await asyncio.sleep(2)
print('%s: goodbye, world!' % threading.current_thread()) print('%s: goodbye, world!' % threading.current_thread())
loop = asyncio.get_event_loop() loop = asyncio.get_event_loop()
......
""" """
异步I/O操作 - asyncio模块 异步I/O操作 - asyncio模块
Version: 0.1 Version: 0.1
Author: 骆昊 Author: 骆昊
Date: 2018-03-21 Date: 2018-03-21
""" """
import asyncio import asyncio
async def wget(host): async def wget(host):
print('wget %s...' % host) print('wget %s...' % host)
connect = asyncio.open_connection(host, 80) connect = asyncio.open_connection(host, 80)
# 异步方式等待连接结果 # 异步方式等待连接结果
reader, writer = await connect reader, writer = await connect
header = 'GET / HTTP/1.0\r\nHost: %s\r\n\r\n' % host header = 'GET / HTTP/1.0\r\nHost: %s\r\n\r\n' % host
writer.write(header.encode('utf-8')) writer.write(header.encode('utf-8'))
# 异步I/O方式执行写操作 # 异步I/O方式执行写操作
await writer.drain() await writer.drain()
while True: while True:
# 异步I/O方式执行读操作 # 异步I/O方式执行读操作
line = await reader.readline() line = await reader.readline()
if line == b'\r\n': if line == b'\r\n':
break break
print('%s header > %s' % (host, line.decode('utf-8').rstrip())) print('%s header > %s' % (host, line.decode('utf-8').rstrip()))
writer.close() writer.close()
loop = asyncio.get_event_loop() loop = asyncio.get_event_loop()
......
""" """
使用协程 - 模拟快递中心派发快递 使用协程 - 模拟快递中心派发快递
Version: 0.1 Version: 0.1
Author: 骆昊 Author: 骆昊
Date: 2018-03-21 Date: 2018-03-21
""" """
from time import sleep from time import sleep
...@@ -13,26 +11,26 @@ from random import random ...@@ -13,26 +11,26 @@ from random import random
def build_deliver_man(man_id): def build_deliver_man(man_id):
total = 0 total = 0
while True: while True:
total += 1 total += 1
print('%d号快递员准备接今天的第%d单.' % (man_id, total)) print('%d号快递员准备接今天的第%d单.' % (man_id, total))
pkg = yield pkg = yield
print('%d号快递员收到编号为%s的包裹.' % (man_id, pkg)) print('%d号快递员收到编号为%s的包裹.' % (man_id, pkg))
sleep(random() * 3) sleep(random() * 3)
def package_center(deliver_man, max_per_day): def package_center(deliver_man, max_per_day):
num = 1 num = 1
deliver_man.send(None) deliver_man.send(None)
# next(deliver_man) # next(deliver_man)
while num <= max_per_day: while num <= max_per_day:
package_id = 'PKG-%d' % num package_id = 'PKG-%d' % num
deliver_man.send(package_id) deliver_man.send(package_id)
num += 1 num += 1
sleep(0.1) sleep(0.1)
deliver_man.close() deliver_man.close()
print('今天的包裹派送完毕!') print('今天的包裹派送完毕!')
dm = build_deliver_man(1) dm = build_deliver_man(1)
......
""" """
使用协程 - 查看协程的状态 使用协程 - 查看协程的状态
Version: 0.1 Version: 0.1
Author: 骆昊 Author: 骆昊
Date: 2018-03-21 Date: 2018-03-21
""" """
from time import sleep from time import sleep
...@@ -13,31 +11,31 @@ from inspect import getgeneratorstate ...@@ -13,31 +11,31 @@ from inspect import getgeneratorstate
def build_deliver_man(man_id): def build_deliver_man(man_id):
total = 0 total = 0
while True: while True:
total += 1 total += 1
print('%d号快递员准备接今天的第%d单.' % (man_id, total)) print('%d号快递员准备接今天的第%d单.' % (man_id, total))
pkg = yield pkg = yield
print('%d号快递员收到编号为%s的包裹.' % (man_id, pkg)) print('%d号快递员收到编号为%s的包裹.' % (man_id, pkg))
sleep(0.5) sleep(0.5)
def package_center(deliver_man, max_per_day): def package_center(deliver_man, max_per_day):
num = 1 num = 1
# 创建状态(GEN_CREATED) - 等待开始执行 # 创建状态(GEN_CREATED) - 等待开始执行
print(getgeneratorstate(deliver_man)) print(getgeneratorstate(deliver_man))
deliver_man.send(None) deliver_man.send(None)
# 挂起状态(GEN_SUSPENDED) - 在yield表达式处暂停 # 挂起状态(GEN_SUSPENDED) - 在yield表达式处暂停
print(getgeneratorstate(deliver_man)) print(getgeneratorstate(deliver_man))
# next(deliver_man) # next(deliver_man)
while num <= max_per_day: while num <= max_per_day:
package_id = 'PKG-%d' % num package_id = 'PKG-%d' % num
deliver_man.send(package_id) deliver_man.send(package_id)
num += 1 num += 1
deliver_man.close() deliver_man.close()
# 结束状态(GEN_CLOSED) - 执行完毕 # 结束状态(GEN_CLOSED) - 执行完毕
print(getgeneratorstate(deliver_man)) print(getgeneratorstate(deliver_man))
print('今天的包裹派送完毕!') print('今天的包裹派送完毕!')
dm = build_deliver_man(1) dm = build_deliver_man(1)
......
""" """
生成器 - 生成器语法 生成器 - 生成器语法
Version: 0.1 Version: 0.1
Author: 骆昊 Author: 骆昊
Date: 2018-03-21 Date: 2018-03-21
""" """
seq = [x * x for x in range(10)] seq = [x * x for x in range(10)]
...@@ -14,12 +12,12 @@ print(seq) ...@@ -14,12 +12,12 @@ print(seq)
gen = (x * x for x in range(10)) gen = (x * x for x in range(10))
print(gen) print(gen)
for x in gen: for x in gen:
print(x) print(x)
num = 10 num = 10
gen = (x ** y for x, y in zip(range(1, num), range(num - 1, 0, -1))) gen = (x ** y for x, y in zip(range(1, num), range(num - 1, 0, -1)))
print(gen) print(gen)
n = 1 n = 1
while n < num: while n < num:
print(next(gen)) print(next(gen))
n += 1 n += 1
""" """
生成器 - 使用yield关键字 生成器 - 使用yield关键字
Version: 0.1 Version: 0.1
Author: 骆昊 Author: 骆昊
Date: 2018-03-21 Date: 2018-03-21
""" """
def fib(num): def fib(num):
n, a, b = 0, 0, 1 n, a, b = 0, 0, 1
while n < num: while n < num:
yield b yield b
a, b = b, a + b a, b = b, a + b
n += 1 n += 1
for x in fib(20): for x in fib(20):
print(x) print(x)
""" """
使用Process类创建多个进程 使用Process类创建多个进程
Version: 0.1 Version: 0.1
Author: 骆昊 Author: 骆昊
Date: 2018-03-20 Date: 2018-03-20
""" """
# 通过下面程序的执行结果可以证实 父进程在创建子进程时复制了进程及其数据结构 # 通过下面程序的执行结果可以证实 父进程在创建子进程时复制了进程及其数据结构
......
""" """
实现进程间的通信 实现进程间的通信
Version: 0.1 Version: 0.1
Author: 骆昊 Author: 骆昊
Date: 2018-03-20 Date: 2018-03-20
""" """
import multiprocessing import multiprocessing
import os import os
def sub_task(queue): def sub_task(queue):
print('子进程进程号:', os.getpid()) print('子进程进程号:', os.getpid())
counter = 0 counter = 0
while counter < 1000: while counter < 1000:
queue.put('Pong') queue.put('Pong')
counter += 1 counter += 1
if __name__ == '__main__': if __name__ == '__main__':
print('当前进程号:', os.getpid()) print('当前进程号:', os.getpid())
queue = multiprocessing.Queue() queue = multiprocessing.Queue()
p = multiprocessing.Process(target=sub_task, args=(queue,)) p = multiprocessing.Process(target=sub_task, args=(queue,))
p.start() p.start()
counter = 0 counter = 0
while counter < 1000: while counter < 1000:
queue.put('Ping') queue.put('Ping')
counter += 1 counter += 1
p.join() p.join()
print('子任务已经完成.') print('子任务已经完成.')
for _ in range(2000): for _ in range(2000):
print(queue.get(), end='') print(queue.get(), end='')
""" """
创建进程调用其他程序 创建进程调用其他程序
Version: 0.1 Version: 0.1
Author: 骆昊 Author: 骆昊
Date: 2018-03-20 Date: 2018-03-20
""" """
import subprocess import subprocess
import sys import sys
def main(): def main():
# 通过sys.argv获取命令行参数 # 通过sys.argv获取命令行参数
if len(sys.argv) > 1: if len(sys.argv) > 1:
# 第一个命令行参数是程序本身所以从第二个开始取 # 第一个命令行参数是程序本身所以从第二个开始取
for index in range(1, len(sys.argv)): for index in range(1, len(sys.argv)):
try: try:
# 通过subprocess模块的call函数启动子进程 # 通过subprocess模块的call函数启动子进程
status = subprocess.call(sys.argv[index]) status = subprocess.call(sys.argv[index])
except FileNotFoundError: except FileNotFoundError:
print('不能执行%s命令' % sys.argv[index]) print('不能执行%s命令' % sys.argv[index])
else: else:
print('请使用命令行参数指定要执行的进程') print('请使用命令行参数指定要执行的进程')
if __name__ == '__main__': if __name__ == '__main__':
main() main()
""" """
使用多线程的情况 - 模拟多个下载任务 使用多线程的情况 - 模拟多个下载任务
Version: 0.1 Version: 0.1
Author: 骆昊 Author: 骆昊
Date: 2018-03-20 Date: 2018-03-20
""" """
from random import randint from random import randint
...@@ -15,29 +13,29 @@ import _thread ...@@ -15,29 +13,29 @@ import _thread
def download_task(filename): def download_task(filename):
print('开始下载%s...' % filename) print('开始下载%s...' % filename)
time_to_download = randint(5, 10) time_to_download = randint(5, 10)
print('剩余时间%d秒.' % time_to_download) print('剩余时间%d秒.' % time_to_download)
sleep(time_to_download) sleep(time_to_download)
print('%s下载完成!' % filename) print('%s下载完成!' % filename)
def shutdown_hook(start): def shutdown_hook(start):
end = time() end = time()
print('总共耗费了%.3f秒.' % (end - start)) print('总共耗费了%.3f秒.' % (end - start))
def main(): def main():
start = time() start = time()
# 将多个下载任务放到多个线程中执行 # 将多个下载任务放到多个线程中执行
thread1 = _thread.start_new_thread(download_task, ('Python从入门到住院.pdf',)) thread1 = _thread.start_new_thread(download_task, ('Python从入门到住院.pdf',))
thread2 = _thread.start_new_thread(download_task, ('Peking Hot.avi',)) thread2 = _thread.start_new_thread(download_task, ('Peking Hot.avi',))
# 注册关机钩子在程序执行结束前计算执行时间 # 注册关机钩子在程序执行结束前计算执行时间
atexit.register(shutdown_hook, start) atexit.register(shutdown_hook, start)
if __name__ == '__main__': if __name__ == '__main__':
main() main()
# 执行这里的代码会引发致命错误(不要被这个词吓到) 因为主线程结束后下载线程再想执行就会出问题 # 执行这里的代码会引发致命错误(不要被这个词吓到) 因为主线程结束后下载线程再想执行就会出问题
# 需要说明一下 由于_thread模块属于比较底层的线程操作而且不支持守护线程的概念 # 需要说明一下 由于_thread模块属于比较底层的线程操作而且不支持守护线程的概念
......
""" """
使用多线程的情况 - 模拟多个下载任务 使用多线程的情况 - 模拟多个下载任务
Version: 0.1 Version: 0.1
Author: 骆昊 Author: 骆昊
Date: 2018-03-20 Date: 2018-03-20
""" """
from random import randint from random import randint
...@@ -14,23 +12,23 @@ from time import time, sleep ...@@ -14,23 +12,23 @@ from time import time, sleep
def download_task(filename): def download_task(filename):
print('开始下载%s...' % filename) print('开始下载%s...' % filename)
time_to_download = randint(5, 10) time_to_download = randint(5, 10)
sleep(time_to_download) sleep(time_to_download)
print('%s下载完成! 耗费了%d秒' % (filename, time_to_download)) print('%s下载完成! 耗费了%d秒' % (filename, time_to_download))
def main(): def main():
start = time() start = time()
thread1 = Thread(target=download_task, args=('Python从入门到住院.pdf',)) thread1 = Thread(target=download_task, args=('Python从入门到住院.pdf',))
thread1.start() thread1.start()
thread2 = Thread(target=download_task, args=('Peking Hot.avi',)) thread2 = Thread(target=download_task, args=('Peking Hot.avi',))
thread2.start() thread2.start()
thread1.join() thread1.join()
thread2.join() thread2.join()
end = time() end = time()
print('总共耗费了%.3f秒' % (end - start)) print('总共耗费了%.3f秒' % (end - start))
if __name__ == '__main__': if __name__ == '__main__':
main() main()
""" """
使用多线程的情况 - 模拟多个下载任务 使用多线程的情况 - 模拟多个下载任务
Version: 0.1 Version: 0.1
Author: 骆昊 Author: 骆昊
Date: 2018-03-20 Date: 2018-03-20
""" """
from random import randint from random import randint
...@@ -15,33 +13,33 @@ import threading ...@@ -15,33 +13,33 @@ import threading
class DownloadTask(threading.Thread): class DownloadTask(threading.Thread):
def __init__(self, filename): def __init__(self, filename):
super().__init__() super().__init__()
self._filename = filename self._filename = filename
def run(self): def run(self):
print('开始下载%s...' % self._filename) print('开始下载%s...' % self._filename)
time_to_download = randint(5, 10) time_to_download = randint(5, 10)
print('剩余时间%d秒.' % time_to_download) print('剩余时间%d秒.' % time_to_download)
sleep(time_to_download) sleep(time_to_download)
print('%s下载完成!' % self._filename) print('%s下载完成!' % self._filename)
def main(): def main():
start = time() start = time()
# 将多个下载任务放到多个线程中执行 # 将多个下载任务放到多个线程中执行
# 通过自定义的线程类创建线程对象 线程启动后会回调执行run方法 # 通过自定义的线程类创建线程对象 线程启动后会回调执行run方法
thread1 = DownloadTask('Python从入门到住院.pdf') thread1 = DownloadTask('Python从入门到住院.pdf')
thread1.start() thread1.start()
thread2 = DownloadTask('Peking Hot.avi') thread2 = DownloadTask('Peking Hot.avi')
thread2.start() thread2.start()
thread1.join() thread1.join()
thread2.join() thread2.join()
end = time() end = time()
print('总共耗费了%.3f秒' % (end - start)) print('总共耗费了%.3f秒' % (end - start))
if __name__ == '__main__': if __name__ == '__main__':
main() main()
# 请注意通过threading.Thread创建的线程默认是非守护线程 # 请注意通过threading.Thread创建的线程默认是非守护线程
""" """
使用多线程的情况 - 耗时间的任务在独立的线程中执行 使用多线程的情况 - 耗时间的任务在独立的线程中执行
Version: 0.1 Version: 0.1
Author: 骆昊 Author: 骆昊
Date: 2018-03-20 Date: 2018-03-20
""" """
import time import time
......
""" """
多个线程共享数据 - 没有锁的情况 多个线程共享数据 - 没有锁的情况
Version: 0.1 Version: 0.1
Author: 骆昊 Author: 骆昊
Date: 2018-03-20 Date: 2018-03-20
""" """
from time import sleep from time import sleep
......
""" """
多个线程共享数据 - 有锁的情况 多个线程共享数据 - 有锁的情况
Version: 0.1 Version: 0.1
Author: 骆昊 Author: 骆昊
Date: 2018-03-20 Date: 2018-03-20
""" """
import time import time
...@@ -14,33 +12,33 @@ import threading ...@@ -14,33 +12,33 @@ import threading
class Account(object): class Account(object):
def __init__(self): def __init__(self):
self._balance = 0 self._balance = 0
self._lock = threading.Lock() self._lock = threading.Lock()
def deposit(self, money): def deposit(self, money):
# 获得锁后代码才能继续执行 # 获得锁后代码才能继续执行
self._lock.acquire() self._lock.acquire()
try: try:
new_balance = self._balance + money new_balance = self._balance + money
time.sleep(0.01) time.sleep(0.01)
self._balance = new_balance self._balance = new_balance
finally: finally:
# 操作完成后一定要记着释放锁 # 操作完成后一定要记着释放锁
self._lock.release() self._lock.release()
@property @property
def balance(self): def balance(self):
return self._balance return self._balance
if __name__ == '__main__': if __name__ == '__main__':
account = Account() account = Account()
# 创建100个存款的线程向同一个账户中存钱 # 创建100个存款的线程向同一个账户中存钱
for _ in range(100): for _ in range(100):
threading.Thread(target=account.deposit, args=(1,)).start() threading.Thread(target=account.deposit, args=(1,)).start()
# 等所有存款的线程都执行完毕 # 等所有存款的线程都执行完毕
time.sleep(2) time.sleep(2)
print('账户余额为: ¥%d元' % account.balance) print('账户余额为: ¥%d元' % account.balance)
# 想一想结果为什么不是我们期望的100元 # 想一想结果为什么不是我们期望的100元
""" """
不使用多线程的情况 - 模拟多个下载任务 不使用多线程的情况 - 模拟多个下载任务
Version: 0.1 Version: 0.1
Author: 骆昊 Author: 骆昊
Date: 2018-03-20 Date: 2018-03-20
""" """
from random import randint from random import randint
......
""" """
不使用多线程的情况 - 耗时间的任务阻塞主事件循环 不使用多线程的情况 - 耗时间的任务阻塞主事件循环
Version: 0.1 Version: 0.1
Author: 骆昊 Author: 骆昊
Date: 2018-03-20 Date: 2018-03-20
""" """
import time import time
......
""" """
套接字 - 基于TCP协议创建时间服务器 套接字 - 基于TCP协议创建时间服务器
Version: 0.1 Version: 0.1
Author: 骆昊 Author: 骆昊
Date: 2018-03-22 Date: 2018-03-22
""" """
from socket import * from socket import *
...@@ -16,10 +14,10 @@ server.bind(('localhost', 6789)) ...@@ -16,10 +14,10 @@ server.bind(('localhost', 6789))
server.listen() server.listen()
print('服务器已经启动正在监听客户端连接.') print('服务器已经启动正在监听客户端连接.')
while True: while True:
client, addr = server.accept() client, addr = server.accept()
print('客户端%s:%d连接成功.' % (addr[0], addr[1])) print('客户端%s:%d连接成功.' % (addr[0], addr[1]))
currtime = localtime(time()) currtime = localtime(time())
timestr = strftime('%Y-%m-%d %H:%M:%S', currtime) timestr = strftime('%Y-%m-%d %H:%M:%S', currtime)
client.send(timestr.encode('utf-8')) client.send(timestr.encode('utf-8'))
client.close() client.close()
server.close() server.close()
""" """
套接字 - 基于TCP协议创建时间客户端 套接字 - 基于TCP协议创建时间客户端
Version: 0.1 Version: 0.1
Author: 骆昊 Author: 骆昊
Date: 2018-03-22 Date: 2018-03-22
""" """
from socket import * from socket import *
...@@ -13,8 +11,8 @@ from socket import * ...@@ -13,8 +11,8 @@ from socket import *
client = socket(AF_INET, SOCK_STREAM) client = socket(AF_INET, SOCK_STREAM)
client.connect(('localhost', 6789)) client.connect(('localhost', 6789))
while True: while True:
data = client.recv(1024) data = client.recv(1024)
if not data: if not data:
break break
print(data.decode('utf-8')) print(data.decode('utf-8'))
client.close() client.close()
""" """
套接字 - 基于UDP协议Echo服务器 套接字 - 基于UDP协议Echo服务器
Version: 0.1 Version: 0.1
Author: 骆昊 Author: 骆昊
Date: 2018-03-22 Date: 2018-03-22
""" """
from socket import * from socket import *
from time import * from time import *
server = socket(AF_INET, SOCK_DGRAM) server = socket(AF_INET, SOCK_DGRAM)
server.bind(('localhost', 6789)) server.bind(('localhost', 6789))
while True: while True:
data, addr = server.recvfrom(1024) data, addr = server.recvfrom(1024)
server.sendto(data, addr) server.sendto(data, addr)
server.close() server.close()
""" """
套接字 - 基于UDP协议创建Echo客户端 套接字 - 基于UDP协议创建Echo客户端
Version: 0.1 Version: 0.1
Author: 骆昊 Author: 骆昊
Date: 2018-03-22 Date: 2018-03-22
""" """
from socket import * from socket import *
client = socket(AF_INET, SOCK_DGRAM) client = socket(AF_INET, SOCK_DGRAM)
while True: while True:
data_str = input('请输入: ') data_str = input('请输入: ')
client.sendto(data_str.encode('utf-8'), ('localhost', 6789)) client.sendto(data_str.encode('utf-8'), ('localhost', 6789))
data, addr = client.recvfrom(1024) data, addr = client.recvfrom(1024)
data_str = data.decode('utf-8') data_str = data.decode('utf-8')
print('服务器回应:', data_str) print('服务器回应:', data_str)
if data_str == 'bye': if data_str == 'bye':
break break
client.close() client.close()
""" """
使用socketserver模块创建时间服务器 使用socketserver模块创建时间服务器
Version: 0.1 Version: 0.1
Author: 骆昊 Author: 骆昊
Date: 2018-03-22 Date: 2018-03-22
""" """
from socketserver import TCPServer, StreamRequestHandler from socketserver import TCPServer, StreamRequestHandler
from time import * from time import *
class EchoRequestHandler(StreamRequestHandler): class EchoRequestHandler(StreamRequestHandler):
def handle(self): def handle(self):
currtime = localtime(time()) currtime = localtime(time())
timestr = strftime('%Y-%m-%d %H:%M:%S', currtime) timestr = strftime('%Y-%m-%d %H:%M:%S', currtime)
self.wfile.write(timestr.encode('utf-8')) self.wfile.write(timestr.encode('utf-8'))
server = TCPServer(('localhost', 6789), EchoRequestHandler) server = TCPServer(('localhost', 6789), EchoRequestHandler)
......
""" """
创建Excel文件 创建Excel文件
Version: 0.1 Version: 0.1
Author: 骆昊 Author: 骆昊
Date: 2018-03-26 Date: 2018-03-26
""" """
from openpyxl import Workbook from openpyxl import Workbook
from openpyxl.worksheet.table import Table, TableStyleInfo from openpyxl.worksheet.table import Table, TableStyleInfo
......
""" """
读取Excel文件 读取Excel文件
Version: 0.1 Version: 0.1
Author: 骆昊 Author: 骆昊
Date: 2018-03-26 Date: 2018-03-26
""" """
from openpyxl import load_workbook from openpyxl import load_workbook
...@@ -16,7 +14,7 @@ print(workbook.sheetnames) ...@@ -16,7 +14,7 @@ print(workbook.sheetnames)
sheet = workbook[workbook.sheetnames[0]] sheet = workbook[workbook.sheetnames[0]]
print(sheet.title) print(sheet.title)
for row in range(2, 7): for row in range(2, 7):
for col in range(65, 70): for col in range(65, 70):
cell_index = chr(col) + str(row) cell_index = chr(col) + str(row)
print(sheet[cell_index].value, end='\t') print(sheet[cell_index].value, end='\t')
print() print()
""" """
创建PDF文件 创建PDF文件
Version: 0.1 Version: 0.1
Author: 骆昊 Author: 骆昊
Date: 2018-03-26 Date: 2018-03-26
"""
""" \ No newline at end of file
import PyPDF2
""" """
读取PDF文件 读取PDF文件
Version: 0.1 Version: 0.1
Author: 骆昊 Author: 骆昊
Date: 2018-03-26 Date: 2018-03-26
""" """
from PyPDF2 import PdfFileReader from PyPDF2 import PdfFileReader
with open('./res/Python课程大纲.pdf', 'rb') as f: with open('./res/Python课程大纲.pdf', 'rb') as f:
reader = PdfFileReader(f, strict=False) reader = PdfFileReader(f, strict=False)
print(reader.numPages) print(reader.numPages)
if reader.isEncrypted: if reader.isEncrypted:
reader.decrypt('') reader.decrypt('')
current_page = reader.getPage(5) current_page = reader.getPage(5)
print(current_page) print(current_page)
print(current_page.extractText()) print(current_page.extractText())
""" """
使用pillow操作图像 使用pillow操作图像
Version: 0.1 Version: 0.1
Author: 骆昊 Author: 骆昊
Date: 2018-03-26 Date: 2018-03-26
""" """
from PIL import Image from PIL import Image
img = Image.open('./res/guido.jpg') img = Image.open('./res/guido.jpg')
...@@ -19,8 +16,8 @@ img.save('./res/guido.png') ...@@ -19,8 +16,8 @@ img.save('./res/guido.png')
img2 = Image.open('./res/guido.png') img2 = Image.open('./res/guido.png')
img3 = img2.crop((335, 435, 430, 615)) img3 = img2.crop((335, 435, 430, 615))
for x in range(4): for x in range(4):
for y in range(5): for y in range(5):
img2.paste(img3, (95 * y , 180 * x)) img2.paste(img3, (95 * y , 180 * x))
img2.resize((img.size[0] // 2, img.size[1] // 2)) img2.resize((img.size[0] // 2, img.size[1] // 2))
img2.rotate(90) img2.rotate(90)
img2.save('./res/guido2.png') img2.save('./res/guido2.png')
""" """
创建Word文件 创建Word文件
Version: 0.1 Version: 0.1
Author: 骆昊 Author: 骆昊
Date: 2018-03-26 Date: 2018-03-26
"""
""" \ No newline at end of file
""" """
读取Word文件 读取Word文件
Version: 0.1 Version: 0.1
Author: 骆昊 Author: 骆昊
Date: 2018-03-26 Date: 2018-03-26
""" """
from docx import Document from docx import Document
...@@ -17,5 +15,5 @@ print(doc.paragraphs[0].text) ...@@ -17,5 +15,5 @@ print(doc.paragraphs[0].text)
content = [] content = []
for para in doc.paragraphs: for para in doc.paragraphs:
content.append(para.text) content.append(para.text)
print(''.join(content)) print(''.join(content))
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment