Commit 6411875f authored by jackfrued's avatar jackfrued

更正了部分文档和代码

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