Python选修课学习笔记

python笔记

1.Hello python 之 温度转换实例

a = input()
if a[0] in ['$']:
    R = (eval(a[1:])) * 6.78
    print("¥{:.2f}".format(R))
elif a[0:3] == 'USD':
    R = (eval(a[3:])) * 6.78
    print("RMB{:.2f}".format(R))
elif a[0] in ['¥']:
    U = (eval(a[1:])) / 6.78
    print("${:.2f}".format(U))
elif a[0:3] == 'RMB':
    U = (eval(a[3:])) / 6.78
    print("USD{:.2f}".format(U))

2.Turtle库的使用 之 蟒蛇绘制实例

import turtle    #导入turtle库
turtle.setup(w,h,x,y)  800,400  #设置画布的大小

turtle.goto(100,100)
turtle.goto(100,-100)
turtle.fd(d)  # 前进 d>0 向前 d<0 后  forward(d)
turtle.bk(d)  # 后退
turtle.circle(r,jiaodui) # 弧度 走曲线
turtle.seth(jiaodu)  # 绝对角度
turtle.left() .right()   # 海龟角度

turtle.colormode(mode)  # 小数/ 整数模式的切换
from turtle import *   # 可能会出现 函数重名的问题
import turtle as t   # 最优解 防重名 防冗余
turtle.penup()   .pu()   # 起笔
pendown() .pd()  # 落笔
pensize(w)
pencolor("xianse") (t,g,b) ((r,g,b))
for 变量 in range(次数):
 执行语句;     # 从0到 次数-1
range(n)      # 从0到n-1;
range(m,n);     # 从m 到 n-1; 共n-m个
L
import turtle as t
t.setup(800,400)
t.pu()
t.fd(-250)
t.pd()
# t.circle(-40)
t.width(25)
t.pencolor("yellow")
t.seth(-40)
for i in range(4):
    t.circle(40,80)
    t.circle(-40,80)
t.circle(40,80/2)
t.fd(40)
t.circle(16,180)
t.fd(40 * 2/3)
t.done()

3.天天向上的力量

千分之一的力量

dayup = pow(1.001,365)    # 1.001 ** 365
daydown = 0.999 ** 365
print("向上的: {:.2f},向下的: {:.2f}".format(dayup,daydown))

千分之五,和 百分之一的力量

dayt = 0.005 # 换成0.01
dayup = pow(1 + dayt,365)    # 1.001 ** 365
daydown = (1 - dayt) ** 365
print("向上的: {:.2f},向下的: {:.2f}".format(dayup,daydown))

用函数

def dayU(dayt):
 dayup = pow(1 + dayt,365)    # 1.001 ** 365
 daydown = (1 - dayt) ** 365
 print("向上的: {:.2f},向下的: {:.2f}".format(dayup,daydown))

dayU(0.005)

工作日的力量 工作5天 休息2天

def dayUP():
 dayup = 1.0
 dayfactor = 0.01
 daydown = 0.001
 for i in range(365):
    # i % 7 = 0,1,2,3,4,5,6
    if i % 7 in [0,6]:
        dayup  =  dayup * (1 - daydown)
    else :
        dayup = dayup * (1 + dayfactor)
 return dayup

print("天天向上的力量为:{:.2f}。".format(dayUP()))

4.字符串

'python'
"python"
'''PYthon
             语言'''   # 可以换行

<字符串>[M:N]
<字符串>[M:N:K] # 根据步长K对字符串切片 
<字符串>[::-1]  # 字符串逆序输出

转义字符\ " \b 回退 \n 换行 \r 使光标移到本行行首

x + y  # 连接
n * x   # 复制n次
s (notin x  #  s是否是x的子串

获取星期字符串

weekStr = "星期一星期二星期三星期四星期五星期六星期日"
weekId = eval(input("qing ....(1-7): "))
pos = (weekId-1) * 3
print(weekStr[pos:pos + 3])   #切片操作

s = "一二三四五六日"
i = eval(input("qing(1-7):"))
print("星期"+ s[i-1])       #索引操作
len(x)  # 字符串x的长度
str(x)  # 将任意类型的x转换成字符串形式
hex(x) # 整数x 转换成 十六进制
oct(x)  # 整数x 转换成  八进制
chr(x)  # x为Unicode编码 转换成 字符串   chr(10004) 对 :  9801 金牛座
ord(x)  # x为 字符串 ,,,,,,,,,

for  i in range(12):
    print(i,end=",")     #注意 end = ""

#字符串处理方法
str.lower() # 大写转小写
str.upper()  # 小转大
>>> "jtitj*kjgij*gjij".split("*")  # 以“*”为标志,隔开每个字符串
['jtitj', 'kjgij', 'gjij']

str.count(sub) # 字串sub 在str中出现的次数

str.replace(x,k[,count]) # 用k替换x  如果count制定,替换不超过count次

>>> "python".center(20,"=")   # 居中操作,前后空出20位置,并填充“=”
'=======python======='
>>> "= python= ".strip(" =np")  # 删除掉括号中的所有字符
'ytho'
>>> ",".join("12345")
'1,2,3,4,5'        #除最后一个字符外,加",";


  "{1}: ,,, {2}".format("jkk","kmjk")  槽 , 格式化
  : 填充 对齐 宽度  , 精度 类型

5.函数

函数
r = int(input())
def yuan(r):
    area = 3.14*r*r
    return area
def main():
    print("圆的面积为:{}".format(yuan(r)))  #  print(yuan(r))

main()
def info(a,*b): # 可变参数 加上* 的参数,是以元组的形式返回的
    print(a)
    print(b)
info(7,8,9,100)

def foom(a,**b):  # ** 的参数,是以字典的形式返回
    print(a)
    print(b)
foom(10,m=10,n=20)
参数传递 1)按位置传递     2)按名称传递
返回值  1return 2)可以返回多个值 以元组形式(a,b,c)

可以通过global保留字在函数内声明全局变量
组合数据类型 ,如果 局部变量未真是创建,则是全局变量

lambda 关键字 定义函数
f(函数名) = lambda x,y: x+y
>> f(10,5)
>>25

>>f = lambda :"python"
>>print(f())
>>python

6.素数 随机数 π的计算

n = eval(input("请输入一个正整数:"))
for i in range(2,n):
    if n%i == 0:
        print("{}这不是一个素数".format(n))
        break
else :
        print("{}这是一个素数".format(n))
random 库 生成伪随机数  import random
seed(a = None) 例如: see(10)  种子是10
random()  # 生成一个[0.0, 1.0)之间的随机小数
import random
print(random.random())  # 在没有种子时,是以当前系统时间(微秒级别)作为种子来产生随机数,往后很难再现这个随机数;
print("-"*10)
random.seed(10)
print(random.random())
print(random.random())
print(random.random())
print("-"*10)
print(random.random())
print(random.random())
print(random.random())

randint(a,b)  生成 [a,b] 之间的随机数
randrange(m,n[,k]) [10,100) 以k 为步长
getandbits(k) # 生成一个k比特长的随机整数
>>>random.getrandbits(16)
37885
uniform(a, b)
生成一个[a, b]之间的随机小数
>>>random.uniform(10, 100)
13.096321648808136

ls = ["c","java","c++","python"]
print(random.choices(ls))  # 随机选取一个
random.shuffle(ls)  # 打乱顺序
print(ls)

π的计算
pi = 0
n = 1000
for k in range(n):
    pi +=(1/pow(16,k))* (4/(8*k+1)-2/(8*k+4)-1/(8*k+5)-1/(8*k+6))
print(pi)

π的计算
#  蒙特卡罗方法(撒点)
from random import random
import time
# from time import perf_counter
# import time as t
da = 1000*1000
hits = 0.0
start = time.perf_counter()
for i in range(da):
    x,y = random(),random()
    dist = pow(x**2 + y**2,0.5)
    if dist <= 1.0:
        hits += 1
pi = 4 * (hits/da)
print("圆周率为:{}".format(pi))
print("运行时间是:{}s".format(time.perf_counter()-start))

7.循环控制结构

 二分支结构
<表达式1> if <条件> else <表达式2>  表达式 不能为赋值语句;
多分支结构
  if x:
      语句
  elif if y:
      语句
  else  z:
      语句
条件组合
    x and y   ;   x or y  ;  not x

 身体质量指数BMI

weight,height = eval(input("请输入体重(kg)和身高(m)(用逗号隔开):"))
BMI = weight / (height ** 2)
print("您的BMI值为:{:.2f}".format(BMI))
if BMI < 18.5:
    print("国际:{},国内: {}".format("偏瘦","偏瘦"))

遍历循环
  计数循环
for i in range(3):  #从0到n-1; 共n次
    print("i = ",i)
print("---------")
for i in range(1,5): # 从1 到 4
    print("i = ",i)
print("---------")
for i in range(1,5,2):
    print("i = ", i)
print("---------")

for c in "python":
    print(c,end = "\t")
print("\n")
for m in [123,"PY",345]:
    print(m,end = ",")

求阶乘
n = int(input("请输入一个整数:"))
fact = 1
i = 1
while i<= n:
    fact *= i
    i += 1
print("{:}的阶乘为:{:}".format(n,fact))

 循环 能 和 else 搭配使用  若有break;else 内容 不执行
 for ,,,(while ,,,,)
    ,,,
 else


 Pass 语句(空语句)

8.文本进度条

time
库
import time

time. < b > ()

函数
time()
时间戳
返回浮点数
ctime()
获取当前时间
易读
字符串
gmtime()
计算机可处理的时间格式

时间格式化

strftime()(tp1, ts)
tp1是格式化模板字符串
ts是计算机内部时间类型变量
strptime()(ts, tp1)
相反
% Y
年份
% m
月份
% d
日
% B
月份名称
% a
星期缩写
% H
小时24
% I
小时12
% P
上下午
% M
时
% S
秒

程序计时

time.perf_counter()
cpu级别的精确时间
单位秒

>> > start = time.perf_counter()
>> > end = time.perf_counter()
>> > end - start
49.06801359999997
>> >

time.sleep(s)
s是休眠时间
秒
浮点数


def wei():
    sleep(3.3)


简单的文本进度条
import time
print("---执行开始---")
s = 10  #宽度
for i in range( s + 1 ):
    a = "*" * i
    b = "." * ( s - i )
    c = ( i / s ) * 100
    print("{:3.0f} %[{}>{}]".format(c,a,b))
    time.sleep(0.1)
print("---执行结束---")

单行动态刷新   刷新 ,\r --- 让光标返回到行首位置
for i in range(10):
    print("\r" + str(i),end="")
    time.sleep(0.5)
# 刷新的文本进度条
import time
s = 50
print("执行开始".center(s//2,"-"))
start = time.perf_counter()
for i in range( s + 1 ):
    a = "*" * i
    b = "." * ( s - i )
    c = ( i / s ) * 100
    dur = time.perf_counter() - start
    print("\r{:3.0f} %[{}>{}] {:.2f}s".format(c,a,b,dur),end = "")
    time.sleep(0.05)
print ("\n"+"执行结束".center(s//2,"-"))

9.递归 斐波那契数列 汉诺塔实例

def fac(s):   # 利用递归翻转字符串
    if s == "":
        return s
    else :
        return fac(s[1:])+s[0]
print(fac("python"))
  # 斐波那契数列
def f(n):  
    if n==1 or n == 2:
        return 1
    else :
        return f(n-1) + f(n-2)
# 汉诺塔问题
count = 0
def hai(n,s,d,m):          # 汉诺塔 n 圆盘数量 s 开始柱子 d 目标柱子  m 中间柱子
    global count
    if n == 1:
       print("{}:{}->{}".format(1,s,d))
       count += 1
    else:
        hai(n-1,s,m,d)
        print("{}:{}->{}".format(n,s,d))
        count += 1
        hai(n-1,m,d,s)
hai(3,"A","C","B")
print(count)

10.七段数码管的绘制

import turtle
import time
# 绘制一条直线
def Drawline(draw):
    """
    if draw:
        turtle.pendown()
    else:
        turtle.penup()
        """
    # 表达式1 if 条件 else 表达式2
    DrawGap()
    turtle.pendown() if draw else turtle.penup()
    turtle.fd(40) # 40像素
    DrawGap()
    turtle.right(90)
# Drawline(True)
def DrawGap():
    turtle.penup()
    turtle.fd(5)
def DrawDigit(digit):
    Drawline(True) if digit in [2,3,4,5,6,8,9] else Drawline(False)
    Drawline(True) if digit in [0,1, 3, 4, 5, 6,7,8, 9] else Drawline(False)
    Drawline(True) if digit in [0,2, 3,5, 6, 8,] else Drawline(False)
    Drawline(True) if digit in [0,2,6,8] else Drawline(False)
    turtle.left(90)
    Drawline(True) if digit in [0,4,5,6,8,9] else Drawline(False)
    Drawline(True) if digit in [0,2, 3, 5, 6,7, 8, 9] else Drawline(False)
    Drawline(True) if digit in [0,1,2,3,4,7,8,9] else Drawline(False)
    turtle.right(180)
    turtle.penup()
    turtle.fd(20)
def DrawDate(date): # 2020-11+30=
    for i in date:
        if i == "-":
            turtle.write("年",font = ("宋体",24,"normal"))
            turtle.fd(40)
            turtle.pencolor("green")
        elif  i =="+":
            turtle.write("月", font=("宋体", 18, "normal"))
            turtle.fd(40)
            turtle.pencolor("blue")
        elif i == "=":
            turtle.write("日", font=("宋体", 18, "normal"))
        else :
            DrawDigit(eval(i))
def main():
    turtle.setup(800,350)
    turtle.penup()
    turtle.fd(-200)
    turtle.pensize(5)
    turtle.pencolor("red")
    curtime = time.gmtime()  # 获取系统时间
    DrawDate(time.strftime("%Y-%m+%d=",curtime))  # 构建模板 2020-11+30=
main()
turtle.hideturtle()
turtle.done()


11.科赫雪花小包裹

# 利用科赫曲线
import turtle as t
def kehe(size,n):
    if n == 0:
        t.fd(size)
    else:
        for i in [0,60,-120,60]:
            t.left(i)
            kehe(size/3,n-1)
def main():
    t.setup(600,600)
    t.penup()
    t.goto(-200,100)
    t.pendown()
    t.pensize(2)
    l = 3
    kehe(400,l)
    t.right(120)
    kehe(400, l)
    t.right(120)
    kehe(400, l)
    t.hideturtle() # 去除结束时的小海龟身影
    # t.sleep(0)    
    t.done()       # 等待用户手动关闭运行界面
main()

12.列表的增删改查

ls1 = [123,'a','b','c']
ls2 = list("python")
# 增加
print("---增加---")
ls1.append(456)
ls2.insert(2,"abc")
ls1+= ls2
print(ls1)
print(ls2)
print("---修改---")
ls1[-1] = "python"
print(ls1)
print("---删除---")
ls1.pop(4)
print(ls1)
ls1.remove("b")
print(ls1)

lt = list()
lt += ["a",123,"python",23.58,'v']
lt[1] = "hello"
lt.insert(1,"world")
lt.pop(0)
print(lt)
del lt[0:3]
print(lt)
a = lt in 0
print(a)
lt.append(0)
t = lt.index(0)
print(t)
print(len(lt))

13.面向对象

class Cat:
    #  self 由哪个对象调用,就指向那个对象
    def eat(self):
        print("小猫要吃鱼")
        print("%s爱吃鱼" % self.name)
    def drin(self):
        print("小猫爱喝水")
 创建对象      对象变量 =  类名()
 m = Cat()
 m.name = "小懒猫"  # 可以这样做,但不提倡    必须放在调用方法之前,否则会报错
  对象名.方法名()
 m.eat()
 m.drin()
 print(m)   # 查看 对象m 的地址值
 a = id(m)
 print("%d" % a)   # 这两行 也是查看 对象m 的地址 以十进制返回

# 初始化方法
class Cat:
    def __init__(self,newName,color):
        # self.属性值 = 属性的初始值
        self.name = newName  #self.name = "Jerry"
        self.color = color
        print("hello world")
    def eat(self):
         print("%s 爱吃鱼" % self.name)

tom = Cat("Tom","blue")
tom.eat()
print(tom.name)
# 析构方法

class Cat():
    def __init__(self):   # 初始化方法
        self.name = "Jerry"
        print("hello world")
    def __del__(self):   # 析构方法
        print("bye~ bye~")
    def __str__(self):     # 可以自定义内容 返回一个字符串
        return "我是%s" % self.name
tom = Cat()
print("------")
print(tom)  # 打印__str__方法的返回值,若没有该方法,则打印 tom 对象的地址值
# 实例
class Person:
    def __init__(self,newName,newWeight):
        self.name = newName
        self.weight = newWeight
    def run(self):
        self.weight -= 0.5
        print("%s跑步,减重了0.5公斤"%self.name)
    def eat(self):
        self.weight += 1
        print("%s吃东西,增重了1公斤"%self.name)
    def __str__(self):
        return "%s的体重是%.2f公斤" % (self.name,self.weight)
n = Person("小明",74)
print(n)
n.eat()
n.run()
print(n)

# 单继承
class Animal:
    def eat(self):
        print("吃饭")
    def drink(self):
        print("喝水")
    def run(self):
        print("跑步")
    def sleep(self):
        print("睡觉")
class Dog(Animal):
    def bark(self):
        print("吼叫")
class Xiao(Dog):
    def fly(self):
        print("我会飞~")
    def bark(self):    # 重写父类的bark()方法
        super().bark()  # 调用父类的bark()方法
        print("像神一样吼叫........")
        
n = Xiao()
n.fly()
n.eat()
n.bark()

# 多继承
class A:
    def ai(self):
        print("ai....")
class B:
    def bi(self):
        print("bi....")
class C(A,B):
    pass
n = C()
n.ai()
n.bi()

# 私有 get set
class Person:
    def __init__(self,n,y):
        self.name = n
        self.__age = y  # 私有属性  前加“__”
    def getAge(self):
        return self.__age
    def setAge(self,y):
        if y < 0:
            print("输入年龄错误...")
            return
        self.__age = y
    def speak(self):
        print("我叫%s,我今年%s"%(self.name,self.__age))


x = Person("小明",18)
x.speak()
print(x.name)
  # print(x.age)
print(x.getAge())
x.setAge(20)
print(x.getAge())

14.Hamlet词频统计

def getTxt():
    txt = open("hamlet.txt","r").read()
    txt = txt.lower()      # 大写换成小写
    for ch in "!#$%&()*+,-./:;<=>?@[\\]^_‘{|}~":
        txt = txt.replace(ch," ")        # 替换成空格
    return txt
hamletTxt = getTxt()
words = hamletTxt.split() # 以split( 内容) 为标志 ,进行分割
counts = {
    
    }  # 创建字典   单词 : 次数
for word in words:
    '''
        if word in counts:
        counts[word] = counts[word] + 1
    else:
        counts[word] = 1
    '''
    counts[word] = counts.get(word,0) + 1
print(counts)
print(counts.items())
ls = list(counts.items())
print(ls)
ls.sort(key = lambda x:x[1],reverse = True)
for i in range(10):
     word,count = ls[i]
     print("{0:<10}{1:>5}".format(word,count))

15.三国演义词频统计(好像有误)捂脸

import jieba

txt = open("三国演义.txt","r",encoding = "utf-8").read()
excludes = {
    
    "将军","却说","荆州","二人","不可","不能","如此"}
words = jieba.lcut(txt)
counts = {
    
    }  # 创建字典   单词 : 次数
for word in words:
    if len(word) == 1:
        continue
    elif word =="诸葛亮" or word == "孔明曰":
        rword = "孔明"
    elif word =="关公" or word == "云长":
        rword = "关羽"
    elif word =="玄德" or word == "玄德曰":
        rword = "刘备"
    elif word == "孟德" or word == "丞相":
        rword = "曹操"
    else:
        rword = word
    counts[word] = counts.get(word,0) + 1
for word in excludes:
    del counts[word]
ls = list(counts.items())
ls.sort(key = lambda x:x[1],reverse = True)
for i in range(10):
     word,count = ls[i]
     print("{0:<10}{1:>5}".format(word,count))


16.基本统计值的计算

def getNmI():  # 获取用户不定长的输入
    num = []
    n = input("请输入一个值:")
    while n != "":
        num.append(eval(n))
        n = input("请输入一个值:")
    return num
def mean(num):  # 平均值
     s = 0
     for i in num:
         s += i
     return s/len(num)
def dev(num,mean):  # 方差
    s = 0
    for i in num:
        s += (i-mean)**2
    return pow(s/(len(num)-1),0.5)
def media(num):   # 中位数
    new = sorted(num)
    size = len(new)
    if size%2 == 0:
        return (new[size//2]+ new[size//2-1])/2
    else:
        return new[size//2]


num = getNmI()
m = mean(num)
print("平均值:{},方差:{:.2f},中位数:{}".format(mean(num),dev(num,m),media(num)))


猜你喜欢

转载自blog.csdn.net/asacmxjc/article/details/110727746