Python考点大全

#%%递归函数
def fn(num):
    
    if num==1:
        result=1
    else:
        result=fn(num-1)*num
        print(num,result)
        
    return result

n=int(input("请输入一个整数:"))
print("%d!="%n,fn(n))

#%%匿名函数
sunNum=lambda arg1,arg2:arg1+arg2
print(sunNum(20, 40))
print(sunNum(1,2))

#%%匿名函数作为参数
def fun(a,b,opt):
    print("a=%d"%a)
    print("b=%d"%b)
    print("result=",opt(a,b))
    
opt=lambda arg1,arg2:arg1+arg2
fun(11,22,opt)

---------------------------------------------------------------------------------------------------------------------------------

#import turtle
#for x in range(100): 
#    turtle.circle(x)
#    turtle.left(90)
#turtle.mainloop()

#for x in range(100): 
#    print(x)
#    turtle.forward(x)
#    turtle.left(90)
#turtle.mainloop()

problem = input("Enter a math problem, or 'q' to quit:")
while (problem !='q'):
    print("The answer to", problem, "is :", eval(problem))
    problem = input("Enter a math problem, or 'q' to quit:")

#%%
print("中国万岁")

import random,math
def stats(data):
    sum=0.0
    i = 0

    for value in data:
        sum+=data
        i = i+1
    mean = sum/len(i)

    for value in data:
        sum +=(value-mean)**2
    variance = sum/len(i-1)

    std = math.sqrt(variance)

    return(mean,variance,std)
(m,v,s) = stats([random.randint(1,10) for i in range(1000)])
print(m,v,s)
---------------------------------------------------------------------------------------------------------------------------------


#%% 1 open an url
from urllib.request import urlopen

html=urlopen("https://www.pku.edu.cn/department.html#item2").read().decode('utf-8')
print(html)


#%% 2 import regular expression
import re

# find the title
res = re.findall(r"<div (.*?)<br />",html)#.表示除\n之外的任意字符 *表示匹配0-无穷 ?懒惰模式
print("\nPage title is: ",res[0])
for item in res:
    result = re.sub(r"^>[\u4e00-\u9fa5]",'',item)
    print(result)
#%%
# find the paragraphs
res = re.findall(r"<script>(.+?)</script>",html,flags=re.DOTALL)
for item in res:
    print("\nPage paragraph is: ",item)

#%% 3 find href
res = re.findall(r'href="(.*?)"',html)
print("\nAll links: ",res[0])
'''“+”元字符规定其前导字符必须在目标对象中连续出现一次或多次。

“*”元字符规定其前导字符必须在目标对象中出现零次或连续多次。

“?”元字符规定其前导对象必须在目标对象中连续出现零次或一次。'''

---------------------------------------------------------------------------------------------------------------------------------

#%% 1 Introduce multiple ways to download something using python

# http://www.zjhu.edu.cn/resource/img/logo.png
import os
os.makedirs('./img/',exist_ok=True)
IMAGE_URL = "https://www.pku.edu.cn/Uploads/Picture/2019/12/11/s5df09c4db7fda.jpg"

#%% 2 urltrieve Download the image url using urlretrieve - whole file
from urllib.request import urlretrieve
urlretrieve(IMAGE_URL,'./img/image1.png')

#%% 3 request download Using requests.get to download at once - whole file 下载完再写入
import requests
r = requests.get(IMAGE_URL)
with open('./img/image2.png','wb') as f:
    f.write(r.content)

#%% 4 Download chunk by chuck - stream loading - 下载了多少就写入多少
# set stream = true in get() function, more efficient
r = requests.get(IMAGE_URL,stream = True)
with open('./img/image3.png','wb') as f:
    for chunk in r.iter_content(chunk_size=32):
        f.write(chunk)
        
#%% 5 Exercices
---------------------------------------------------------------------------------------------------------------------------------

from bs4 import BeautifulSoup
import requests
import os
os.makedirs('./img/', exist_ok=True)
#%% 1 URL
URL = "https://www.ivsky.com/tupian/xinjiang_t592/"

html = requests.get(URL).text
soup = BeautifulSoup(html, 'lxml')
img_ul = soup.find_all('div', {"class": "il_img"})
print(len(img_ul))
print(img_ul)
#%% 2 Download

for ul in img_ul:
    imgs = ul.find_all("img")
    print(len(imgs))
    # print(imgs)
    for img in imgs:
        url = 'https:'+img['src']
        # print(url)
        r = requests.get(url, stream=True)
        image_name = url.split('/')[-1]
        print(image_name)
        with open('./img/%s' % image_name, 'wb') as f:
            for chunk in r.iter_content(chunk_size=128):
                f.write(chunk)
        print('Saved %s' % image_name)
#%% 3 Download with re
import re
img_ul = soup.find_all("img",{"src":re.compile(".*?\.jpg")})
print(len(img_ul))

for ul in img_ul:
    # print(ul['src'])
    url = 'https:'+ul['src']
    # print(url)
    r = requests.get(url, stream=True)
    image_name = url.split('/')[-1]
    # print(image_name)
    with open('./img/%s' % image_name, 'wb') as f:
        for chunk in r.iter_content(chunk_size=128):
            f.write(chunk)
        print('Saved %s' % image_name)
             
------------------------------------------------------------------------------------------------------------------------------

#%% Int
x = 1
print('type of x: ', type(x))
print('id of x:', id(x))

#%% float
y = 2.0
print(type(y))

z = x + y
print(type(z))

#%% function
def add_1(x,y):
    zz = x + y
    return zz

zz = add_1(8,98)
print(zz)

#%% bool
a = True
print(a)

b = False
print(b)

#%%
#help(int)
xx = x.__add__(9)
print(xx)

# bit_length
s = 1235435
print(s.bit_length())


'''
字长:一个字的位数,CPU和内存之间的数据传送单位通常是一个字长,
即CPU一次读/写数据的二进制位数。通常称处理字长位8位数据的CPU,叫做八位机,8位CPU。
常用的字长8位,16位,32位,64位。
字长为8位的编码,称为字节,是计算机中基本的编码单位。


位:最基本的概念,例如1001 0000 1101,其中每一个逻辑0或者1,就是一个位。


字节:16位为一个字,代表计算机处理指令或者数据的二进制书位数,通常称16位是一个字,32位是双字,64位两个双字
1字 = 2字节 = 16位。

'''

#%% logical operator not and or 
a = 5
b = not(a>10)
print(b)

c = (a>1)and(a>10)
print(c)

d = (a>1)or(a>10)
print(d)

#%% remainder
print(10%3) # 求余数
print(10//3) # 求商
print(10/3) # 求值

#%% imaginary number
c = 5+6j #j,not i
d = 10-2j
e = c+d
print(e)
print(type(e))

#%% Container
#--- String----
# x = "I love huzhou"
# print(x)

# x = """ fjadsljfdasklfjkadsl l dsjflkadsjfklads 
# dsakfadsjfhdasjk ksdhfdasjkf"""
# print(x)

# y = 1.9
# x = """Biden urges Senate \n to quickly pass "%0.2f" trillion relif package """%y
# print(x)

# x = "Biden urges Senate \n to quickly pass '%0.2f' trillion relif package" %y
# print(x)

# x = 'hello '
# y = 'huzhou univerisy'
# z = x+y
# print(z)
# print(type(z))

# upper lower split join
sr = "Discover Python: today"
print(sr.upper())
print(sr.lower())

print(sr.split())

tp = ('love','china')
print(sr.join(tp))

------------------------------------------------------------------------------------------------------------------------------

#%% heterogenous mutable list
I = [1,2,3,4,5,6,7,8,9]
I[2] = "two"
print(I)
del(I[2])
print(I)
I[1:3] = []
print(I)

#%% 
a = ('a','b',1,2,3)
b = a[1:3]
del(b)

#%% Array
a1 = [[0,3,6],[9,8,7],[9,8,[1,2]]]
print(a1)
print(id(a1))

print(len(a1))
print(len(a1[2][2]))

I.reverse()
print(I)

I.sort()
print(I)

I = [1,2,2,2,3,4,5,6,7,8,9]
print(I.count(2))

print(I.index(2))


#pop take off the last item
print(I)
print(I.pop())
print(I)

I = [0,1,3,4,5,5,6,7,8,9,10]
print(I.pop(3))
print(I)


#%% for loop
'''
for item in container:
    action to repeat for each item in the container
else:
    action to take once we have finished the loop

'''
# for with tuple
t = (0,5,6,7,8,9)
count = 0
for num in t:
    count+=num
    print("count:",count,"; num:",num)
    
    if num%2:
        print('Remainder is: ',num%2)
        continue
        print("oooooooo")
    else:
        print('jump over countinue!')
    
    print("hahahaha")  
else:
    print("else in for")
print("out of for and then count is"+str(count))    
    
#%% for with string
st = "I love huzhou university"
for c in st:
    print(c)
print("----------")    
for c in st:
    print(c,end="")
    
    
i = 0
j = 0

for c in st:
    j = j + 1
    if c in "uo":
        i = i + 1
        print("once in ou")
    else:
        print("In the segment of else, iteration j = ",j)
print("Out of for, finally i = ",i)


#%% if
'''
if (expression one):
    # Action to take if expression one evalutes True
else:
    # Action to take if expression one evalutes False

'''
i = 10
if(i%2):
    print("Odd number")
else:
    print("Even number")

i = 0
if i>0:
    print('Positive')
elif(i<0):
    print("Negative")
else:
    print("zero")


#%% while
'''
while (expression)
    statements to excute while loop expression is True
else:
    statements to excute while loop expression is False

'''
i = 1 ; x=10
while(i>0):
    i = i + 1 
    x = x-1
    print("i:",i,"x:",x)
    
    if(i>8):
        pass
    if(x<0):
        break
else:
    print("else expression :",i,x)

----------------------------------------------------------------------------------------------------------------------

L1 = [1,2,3]
L1.insert(1,10)
print(L1)
L2 = [6,7,8]
L1.extend(L2)
L3 = L1[:]
print(L1)
print(L3)

L1.remove(8)
print(L1)

L4 = ['I','love','China']
L4.remove('love')
print(L4)

L4[0]=[]
print(L4)

del L4[0]
print(L4)

#%% Dictionary
# 1. Creating a dict
d = {'name':['Obama','Biden'],'age':[42,78,12],1:['China'],2:('USA','France'),(1,):'huzhou'}
print(d) 
print(len(d))
print(type(d))

# 2. Modification
d['age'] = [45,'Thirty']
print(d)

# 3. don't need append, add key and its value directly
d['note'] = [80,30]
print(d)

# 4. creat an empty dict
d1 = {}
print(len(d1))

# 5. del
del d[2]
print(d)

del d

# 6. Creat a dict from list or tuple
I1 = [(0,'zero'),(1,'one'),(2,['two','three'])]
d1 = dict(I1)
print(d1) 

I2 = [[0,'zero'],[1,'one'],[2,['two','three']]]
d2 = dict(I2)
print(d2) 

I3 = ((0,'zero'),(1,'one'),(2,('two','three')))
d3 = dict(I3)
print(d3) 


d4 = dict(zero='0',one=1,two=2)
print(d4)

# error d5 = dict('zero'=0,'one'=1,'two'=2)

# Searching
d = {0:"zero",'one':1,"two":[1,2,3],3:"apple"}
print(d.keys())
print(d.values())

if 0 in d.keys():
    print("True1")

if "two" in d.keys():
    print("True2")

if "apple" in d.values():
    print("True3")

if 1 in d.values():
    print("True4")
    
    
#%% set
s1 = {"apple",0,(1,2),3}
print(s1)
print(type(s1))    
    
# s1.pop()
# print(s1)
    
s2 = {"apple","huzhou",(1,2),4}
print(s2)

s = s1&s2
print(s)
    
s = s1|s2
print(s)
    
s = s1-s2
print(s)

s3 = set([1,"hello",1])
print(s3)

---------------------------------------------------------------------------------------------------------------------------------

# 推导式和生成器推导式
# list = [expression for var in range]
import random #导入random标准库
x = [random.randint(1,10) for i in range(20)]
print(x)

# the same 
y = list(range(20))
print(y)
for i in range(20):
    print(i)
    y[i] = random.randint(1,10)
print(y)

z = [i*0.5 for i in range(20)]
print(z)

price = [100,500,1000,20,40]
sale = [i for i in price if i<500]
print(sale)

list = [(x,y) for x in range(5) if x%2==0 for y in range(5) if y%2 == 1]
print(list)

for x in range(5):
    if x%2==0:
        x = x
        for y in range(5):
            if y%2==1:
                y = y
                print(x,y)
                
                
x = {i:random.randint(1,10)**2 for i in range(20)}
print(x)
                
x = (random.randint(1,10) for i in range(20))
x = tuple(x)
print(x)
         
#%%
def add2num(a, b):
    c=a+b
    d=a-b
    print("函数运行中")
    return [c,d]
    
#调用函数
Value = add2num(2,3)
print(Value)

#%%
#计算三个数之和
def sum_num(a, b, c):
    return a + b + c

#求三个数平均值
def average_num(a, b, c):
    sumResult = sum_num(a, b, c)
    return sumResult / 3

result = average_num(1, 2, 3)
print(result)

#%% 传递

def printString(obj):
    print("原值:",obj)
    obj += obj
#调用函数
print("------------值传递------------")
strslogan = "不忘初心,牢记使命"
print("函数调用前:",strslogan)
printString(strslogan)   #采用不可变对象:字符串
print("函数调用后:",strslogan)
print("------------引用传递------------")
listslogan = ["不忘初心","牢记使命"]
print("函数调用前:",listslogan)
printString(listslogan)  #采用可变对象:列表
print("函数调用后:",listslogan)


#%%
def printSchool(*name):
    print("\n 我想考研的大学:")
    print(name)
    for item in name:
        print(item)

printSchool('北京大学')
printSchool('北京大学','清华大学')
printSchool('北京大学','清华大学','湖师院')

def printProvince(**provinceName):
    print(provinceName)
    for key,value in provinceName.items():
        print(key+"省的简称:"+value)

printProvince(安徽='皖',浙江='浙',河南='豫',江苏='苏')

-----------------------------------------------------------------------------------------------------------------------------

# --------------- 
# order and length 
sr = "1234567899354"
print(sr[0])
print(sr[1]+sr[5])
print(sr[5:9])
print(sr[1:4]+sr[7:8])
print("length of sr",len(sr))

#%% ----------------
# tuple
t1 = (1,2,3)
print(t1,type(t1))

t = ("name","Lili","Point",(560,60),"age",25)
print(t)

t2 = 1,2,3,4
print(t2,type(t2)) 

t3 = tuple((1,2,3))
print(t3,type(t3))

print(t[0])

t4 = (1,2,3)
y = t4[1]+t4[2]
print(y)

#%% -----------------
# packing and unpacking a tuple
x = 1
y = 'a'
z = ("b",2)

zzz = (x,y,z)
print(zzz)

a1,b1,c1 = zzz
print(a1)
print(b1)
print(c1)


#%% List 
I = [0,1,2,3,4,5,6,7,8,9]
print(I,type(I))

el = [] #creat an empty list
print(len(el))

s1 = [1]
print(s1)
print(type(s1))
print(len(s1))


s2 = (1,)
print(s2)
print(type(s2))
print(len(s2))

#%% change type
# Tuple->List
I1 = list((1,2,3,4,5,6,7,8,9))
I2 = [1,2,3,4,5,6,7,8,9]
print(I1)
print(I2)

I3 = (1,2,3,4,5,6,7,8,9)
I4 = list(I3)
print(I3)
print(I4)

#string->list
st1 = "123456789"
st2 = list(st1)
print("value of st1: ",st1)
print("type of st1: ",type(st1))
print("length of st1: ",len(st1))


print("value of st2: ",st2)
print("type of st2: ",type(st2))
print("length of st2: ",len(st2))


#%% Difference between list and tuple
L = [1,2,3]
L[1] = 99
print("List L:",L)

T = (1,2,3)
# Error T[1] = 99
print("Tuple T: ",T)

# list: write it with pencil, you can erase every element;
# tupe: carve it with knife, you can't erase anything.

#%% Accesing items from a list
I = [1,2,3,4,5,6,7,8,9]
print(I[1:5])

print(I[0:-1:2])
print(I[0:-1:3])
print(I[0:20:2])
print(I[0::2])
print(I[-2])

# modify a list
I = []
#I[0] = 1
I.append(1)
print(I)
I[0] = 99
print(I)
I.clear()
print(I)

---------------------------------------------------------------------------------------------------------------------------------

import random,math
def stats(data):
    sum=0.0
    i = 0
    
    for value in data:
        sum+=value
        i = i+1
    print("参数i的最终值:",i)
    print("data的最大值:",max(data))
    print("data的最小值:",min(data))
    mean = sum/len(data)
    
    for value in data:
        sum += (value-mean)**2
    variance = sum/(len(data)-1)
    
    std = math.sqrt(variance)
    
    return(mean,variance,std)
(m,v,s) = stats([random.randint(1,10) for i in range(1000)])
print(m,v,s)

#%%
def run(a, *args):
    # 第一个参数传给了a
    print(a)
    # args是一个元组,里面是第2和3两个参数
    print(args)
    # *args是将这个元组中的元素依次取出来
    print("对args拆包")
    print(*args)  # *args 相当于 a,b = args
    a,b = args
    print(a,b)
    print("将未拆包的数据传给run1")
    run1(args)
    print("将拆包后的数据传给run1")
    run1(*args)
    
def run1(*args):
    print("输出元组")
    print(args)
    print("对元组进行拆包")
    print(*args)


run('Rose','Tome', 'King')
---------------------------------------------------------------------------------------------------------------

圆的计算模块
"""
import math
r = 3

#类
class Circle:
    pass

#函数
def calcuArea():
    s = math.pi*math.pow(r,2)
    print("圆的面积是{}:".format(str(s)))
    
def perimeter():
    l = math.pi*2*r
    print("圆的周长是{}:".format(str(l)))

#主程序
if __name__ == '__main__':
    calcuArea()

-----------------------------------------------------------------------------------------------------------------------------

#%%
import course_9
course_9.calcuArea()
course_9.perimeter()

#%%
import course_9 as ca
ca.calcuArea()

#%%
from course_9 import calcuArea as caa
caa()

#%%
import  sys
print(sys.path)

#%%
import test20220324
test20220324.A.showme()

#%% 常用的模块与包
import random
print(random.random())
print(random.random())

print(random.uniform(10,100))
print(random.uniform(10,100))

print(random.randint(200, 300))
print(random.randint(200, 300))

#%% time
import time
a = time.time()

b = time.gmtime()
print(b)

c = time.localtime()
print(c)

d = time.asctime()
print(d)

e = time.ctime()
print(e)

#%% date
import datetime
print(datetime)
t = datetime.datetime.now()
print(t)

import calendar
cal = calendar.month(2022,5)
print(cal)

--------------------------------------------------------------------------------------------------------------------------------


@author: Administrator
"""

import config.size as x
v = x.length*x.width*x.height
print(v)

#%%

---------------------------------------------------------------------------------------------------------------------------------

#%% 递归函数
def fn(num):
    if num == 1:
        result=1
    else:
        result = fn(num-1)*num
        print(num,result)
        
    return result

n = int(input("请输入一个整数:"))
print("%d!="%n,fn(n))

#%% 匿名函数
sumNum = lambda arg1,arg2: arg1+arg2
print(sumNum(20,40))
print(sumNum(1,2))

#%% 匿名函数作为参数
def fun(a,b,opt):
    print("a = %d"%a)
    print("b = %d"%b)
    print("result = ",opt(a,b))
    
opt = lambda arg1,arg2: arg1*arg2
fun(11,22,opt)

---------------------------------------------------------------------------------------------------------------------------

import numpy as np
array1 = np.array([[1,2,3],[4,5,6],[7,8,9]])
print(array1)
print("Dimension:",array1.ndim)
print('shape:',array1.shape)
print("Size:",array1.size)

#%% 2 dtype
a = np.array([2,9,3],dtype = np.float32)
print(a.dtype)

b = np.array([2,9,3],dtype = np.float32)
print(b.dtype)

#%% 3 attention of empty
a = np.zeros((3,4))
print (a)

b = np.empty((3,4))
print (b)

c = np.ones((3,4))
print (c)

#%% 4 arange
a = np.arange(10,20,2)
print(a)

b = np.arange(12)
print(b)

c = np.arange(12).reshape(3,4)
print(c)

d = np.linspace(1,10,6).reshape(2,3)
print(d)

#%% 5 calculation of vectors
a = np.array([10,20,30,40])
b = np.arange(4)
c = a-b
print(c)
d = a+b
print(d)
e = a*b
print(e)
f = b**2
print(f)

g = 10*np.sin(a)
print(g)

#%% 6 calculation of Matrix
a = np.array([[1,2],[3,4]])
b = np.arange(4).reshape(2,2)
print(a)
print(b)

c = a*b
print(c)

d = np.dot(a,b)
print(d)

e = a.dot(b)
print(e)

f = np.arange(2)
print(f)

g = np.dot(e,f)
print(g)

h = np.random.random((12,4))
print(h)

print(np.sum(h))
print(np.min(h))
print(np.max(h))

print(np.sum(h,axis=0))
print(np.sum(h,axis=1))

#%% 7 median cumsum diff nonzero sort transpose
A = np.random.random((3,4))
print(A)
print(np.mean(A))
print(np.mean(A,axis=0))
print(np.mean(A,axis=1))

B = np.array([1,20,5,9,41,6,8,100]).reshape(2,4)
print(B)
print(np.median(B))

print(np.cumsum(B))
print(np.diff(B))

print(np.nonzero(B))
print(np.sort(B)) #sort by row

print(np.transpose(B))
print(B[1][0])

#%% 8 merge
A = np.array([1,1,1])
B = np.array([2,2,2])

C = np.vstack((A,B))#vertical stack
print(C)

D = np.hstack((A,B))
print(D)

#%% 9 copy and deep copy
a = np.array([[1,2,3],[4,5,6],[7,8,9]])
print(a)

#b=a
b=a
c=a
d=b

a[0]=35
print(d)
print(d is a)
b[1][1]=99
print(d)

b=a.copy()#deep copy
a[0]=100
print(a)
print(b)
print(a is b)

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值