python—入门

循环

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author:Vergil Fu

for i in range(1,10):
    print("Hello vergil!")


count = 1
while True:
    print("Hello vergil!")
    count += 1
    if count > 10:
        break

count_age = 0
age_of_vergil = 25
while count_age < 3:
    age = int(input("the age of vergil is :"))
    if age == age_of_vergil:
        print("well done!")
        break
    else:
        count_age += 1
    if count_age == 3:
        cont_confirm = input("do you want to try it again?Y/N")
        if cont_confirm == "Y":
            count_age = 0
        else:
            break

字符串嵌入变量

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author:Vergil Fu

name = "vergil"
age = 25
job = "IT"
salary = "22"


info1 = '''
-------- info of  %s  -----
Name:%s
Age:%d
Job:%s
Salary:%s
''' % (name,name,age,job,salary)
print(info1)


info2 = '''
-------- info of {_name}  -----
Name:{_name}
Age:{_age}
Job:{_job}
Salary:{_salary}
'''.format(_name=name,
           _age=age,
           _job=job,
           _salary=salary)
print(info2)


info3 =  '''
-------- info of {0} -----
Name:{0}
Age:{1}
Job:{2}
Salary:{3}
'''.format(name,age,job,salary)
print(info3)

 

字典

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author:Vergil Fu
######################key值固定类型字符串,数字或元组,值不固定类型########################

dic1 = {"a":"1","b":"2","c":"3"}
dic1.setdefault("a",5)########################寻找key值a,如果有则返回原来值,如果没有则新增

dic2 = {"a":"4","d":"5","e":"6"}
dic1.update(dic2)#############################更新

dic3 = dict.fromkeys([1,2],[3,{"1":"a"}])#####创建一个空字典,key值自动为1,2,3,4......
seq = ("a","b","c")
dic4 = dict.fromkeys(seq)#####################创建一个空字典,seq为key值
dic5 = dict.fromkeys(seq,10)##################创建一个空字典,seq为key值,10为值

dic2.items()##################################把字典拆成列表

dic5.pop("a")#################################删除key值,如果没给key值就返回default
dic5.popitem()################################删除最后一个值,如果字典为空就报错
del dic5######################################删除整个字典


seq = ("a","b","c")
dic6 = dict.fromkeys(seq,10)
for i in dic6:
    print(i)###################################打印key值
for i,j in dic6.items():
    print(i,j)#################################打印key值和值

列表

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author:Vergil Fu

lis1 = [1,2,3,4,5]

'''
print(lis1) = print(lis1[0:5]) = print(lis1[:5])
print(lis1[4]) = print(lis1[-1])

print(lis1[0:-1]) = print(lis1[0:4])

print(lis1[::5])#################倒数第5个
'''

import copy

lis2 = [1,2,3,[4,5,6]]
lis3 = copy.copy(lis2)###########原列表改变而改变
lis4 = copy.deepcopy(lis2)#######原列表改变也不改变
lis2[3][0] = 7
print(lis3)
print(lis4)

lis5 = [1,2,3,4,5]
lis5.append(1)###################在最后加入一个1
lis5.insert(1,3)#################在第一个后面插入一个3

lis6 = [1,2,3,4,5]
lis6.remove(1)###################移除1
#del lis6[0] = lis6.pop(0)#######删除第一个

lis7 = [1,2,3,4,5]
lis7.index(1)####################数1在第几个
lis7.count(1)####################数1出现了几次
lis7.clear()#####################清空列表
lis7.reverse()###################反转列表

lis8 = [1,2,3,4,5]
#lis8.sort(cmp,key,reverse=False)#排序,cmp--可选参数,key--主要用来比较的元素,reverse--是否反序

lis9 = [1,2,3]
lis10 = [4,5,6]
lis9.extend(lis10)################列表合并

集合

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author:Vergil Fu

list_1 = [1,4,5,7,3,6,7,9]
list_1 = set(list_1)
list_2 = [2,4,6,8]

#交集
print(list_1.intersection(list_2))
print(list_1 & list_2)

#并集
print(list_1.union(list_2))
print(list_2 | list_1)

#差集
print(list_1.difference(list_2))
print(list_2.difference(list_1))
print(list_1 - list_2)

#子集
list_3 = set([1,3,7])
print(list_3.issubset(list_1))
print(list_1.issuperset(list_3))

#对称差集,A△B= (A∪B)-(A∩B)=(A-B)∪(B-A)
print(list_1.symmetric_difference(list_2))
print(list_1 ^ list_2)

list_4 = set([5,6,7,8])
print(list_3.isdisjoint(list_4))#######################如果两个集合间没有交集,则返回True


list_1.add(999)########################################向集合中加入999
list_1.update([888,777,555])###########################向集合中加入

list_1.pop(888)########################################删除888
list_1.discard(888)####################################删除888

字符串

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author:Vergil Fu

name1 = "my name is\t %s and i am %s old"%("vergil",25)

name1.capitalize()#########################################首字母大写
name1.count("v")###########################################数v出现了几次
name1.center(50,"-")#######################################扩展为50个字符,以-填充
name1.endswith("ex")#######################################是否以ex结尾
name1.expandtabs(tabsize=100)##############################将\t转化为空格,tabsize表示转化为多少个空格
name1[name1.find("name"):]#################################从name开始打印


name2 = "my name is {name} and I am {year} old"
name2.format(name = "vergil",year = 25)
name2.format_map(  {'name':'vergil','year':25}  )


'ab23'.isalnum()############################################是否由字母和数字组成
'abA'.isalpha()#############################################是否至少包含一个字母
'1A'.isdecimal()############################################是否只包含十进制字符。这种方法只存在于unicode对象。
'1A'.isdigit()##############################################是否只由数字组成。
'a 1A'.isidentifier()#######################################判读是不是一个合法的标识符
'33A'.isnumeric()###########################################是否只由数字组成
'My Name Is  '.istitle()####################################是否所有首字母大写,其他小写



'My Name Is  '.isprintable()################################检测是否为可打印字符

import string
str = "saf23156eq/#$"
filtered_string = filter(lambda x: x in string.printable, str)####剥离非打印字符


'My Name Is  '.isupper()###########################################是否全部为大写
'+'.join( ['1','2','3'])###########################################中间插入+


name3 = "my name is vergil"
name3.ljust(50,'*')################################################最右边插入*补足50个字符
name3.rjust(50,'-')################################################最左边插入-补足50个字符
'vergil'.lower()###################################################全部小写
'vergil'.upper()###################################################全部大写
'\nvergil'.lstrip()################################################左边去除\n
'vergil\n'.rstrip()################################################右边去除\n
'    vergil\n'.strip()#############################################两边去除空格


p = str.maketrans("abcdefli",'123$@456')
"vergil".translate(p)##############################################制定编码规则并解码


'vergil'.replace('l','L',1)########################################将l替换成L 1次
'vergil'.rfind('l',0,6)############################################找l,从默认0的位置开始找到第6个字符
'1+2+3+4'.split('\n')##############################################以空格为分隔符
'1+2\n+3+4'.splitlines()###########################################以空格分隔行
'vergil'.swapcase()################################################大小字母转换
'vergil'.title()###################################################首字母大写
'vergil'.zfill(50)#################################################50字段长度,用0填充

 

函数

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author:Vergil Fu

#函数
def func1():
    print('in the func1')
    return 0

#过程
def func2():
    print('in the func2')

print(func1())
print(func2())

#内存地址
def func3():
    pass
print(func3)


def test1(x,y,z):
    print(x)
    print(y)
    print(z)
test1(1,2,3)
#test(1,y=2,3)#########################关键字参数不能在位置参数之前


def test2(x,y,z=2):
    print(x)
    print(y)
    print(z)
test2(1,2,3)
test2(1,2)
#test2(1,2,3,4)#########################实参不能比形参多,但可以比形参少


def test3(*args):
    print(args)
test3(1,2,3)############################输出为元组

def test4(**kwargs):
    print(kwargs)
test4(name="vergil",age=25)
test4(**{"name":"vergil","age":25})

def test5(name,*args,**kwargs):
    print(name)
    print(args)
    print(kwargs)
test5("vergil",12,22,age=25,sex="male")


#高阶函数##############################函数嵌套
#1.把函数当做一个实参传给另一个函数
#2.返回值中包含函数名
def add(a,b,f):
    return f(a)+f(b)

res = add(3,-6,abs)
print(res)


#递归###################################自己调用自己
def calc(n):
    print(n)
    if int(n/2) >0:
        return calc( int(n/2) )
    else:
        print("->",n)
calc(10)

读取

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author:Vergil Fu

f = open("yesterday2",'r+',encoding="utf-8") #可读可写,若文件不存在就报错
f = open("yesterday2",'w+',encoding="utf-8") #可读可写,若文件不存在就创建
f = open("yesterday2",'a+',encoding="utf-8") #不覆盖,在最后追加写
f = open("yesterday2",'wb')###################以二进制的方式写入

f.seek(5,0)###################################从开头的位置移动5个单位
f.seek(5,1)###################################从当前位置向右移动5个单位
f.seek(5,2)###################################从末尾向前移动5个单位

#print(f.flush())

count = 0
for line in f:
    if count == 9:
        print('-----------我是分割线----------')
        count += 1
        continue
    print(line)
    count +=1


import sys
with open("yesterday2","r",encoding="utf-8") as f,open("yesterday2.bak","w",encoding="utf-8") as f_new:
    find_str = sys.argv[1]
    replace_str = sys.argv[2]
    for line in f:
        if find_str in line:
            line = line.replace(find_str,replace_str)
        f_new.write(line)


import time
with open("miss","r+",encoding="utf-8") as f:
    for i in f:
        print(i)
        sys.stdout.flush()###################################刷新缓存区
        time.sleep(0.5)

内置函数

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author:Vergil Fu

print( all([1,-5,3]) )################所有真则返回真
print( any([]) )######################有一个真就返回真
a= ascii([1,2,"开外挂开外挂"])########把列表变成字符串

bin(123456)###########################十进制转二级制
bool()################################判断真假

a = bytes("abcde",encoding="utf-8")###字符串原本不可修改,用bytes转为可修改的字符串
b = bytearray("abcde",encoding="utf-8")#改为ACISS码下可修改
b[1] = 100
chr(98)###############################对应ASCIS码表

print(callable())#####################判断是否可调用的

c = "for i in range(10):print(i)"#####将字符串转化为可执行函数
compile(c,"","exec")
exec(c)

divmod(5,3)###########################输出商和余数
eval("abc")###########################把字符串变成字典

calc = lambda n:3 if n<4 else n######一次性的函数
print(calc(10))

res = filter(lambda n:n<4,range(10))##把小于4的全打印出来
for i in res:
    print(i)

res = map(lambda n:n*2,range(10))######################两个效果是一样的
res = [ lambda i:i*2 for i in range(10)]##############两个效果是一样的


import functools
res = functools.reduce( lambda x,y:x*y,range(1,10 ))###从0累加到9
res = functools.reduce( lambda x,y:x*y,range(1,10 ))###阶层
print(res )

a = frozenset([1,4,333,212,33,33,12,4])################冻结,不可编辑
print(globals())#######################################返回所有代码的变量

hash("vergil")#########################################把字符串转换为序号,高效处理庞大数据

hex(123456)############################################转成16进制
oct(123456)############################################转成8进制

pow(5,2)###############################################5**2
round(3.1415926,2)#####################################保留两位小数

a = [-1,-5,5,6,2,3]
print(sorted(a))#######################################排序
b = {"a":1,"b":2,"c":-1}
print(sorted(b.items(),key = lambda x:x[1]))##########按值排序


a = [1,2,3,4,5,6]
b = ['a','b','c','d']
for i in zip(a,b):####################################把两个列表合一块
    print(i)

__import__('decorator')################################import 字符串

序列化与反序列化

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author:Vergil Fu

###初阶
with open("123123.txt","w+",encoding="utf-8") as f:
    f.write(str({"name":"vergil","age":25}))

with open("123123.txt","r+",encoding="utf-8") as f:
    a = eval(f.read())
    print(a["name"])


###json########################是所有语言通用的,不同语言做交互,只能处理简单的数据
import json
with open("123123.txt","w+",encoding="utf-8") as f:
    f.write(json.dumps({"name":"vergil","age":25}))

with open("123123.txt","r+",encoding="utf-8") as f:
    a = json.loads(f.read())
    print(a["name"])


###pickle######################处理复杂数据,转为二进制
import pickle

def hello(name):
    print("hello %s"%name)
hello("vergil")
func = hello

with open("123123123.txt","wb") as f:
    f.write(pickle.dumps({"name":"vergil","age":25,"func":func}))
    #pickle.dump({"name":"vergil","age":25,"func":func},f)##############等价

with open("123123123.txt","rb") as f:
    b = pickle.loads(f.read())
    #b = pickle.load(f)#################################################等价
    b["func"]("alice")

 生成器

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author:Vergil Fu

# 只有在调用是才生成数据
# 只记录当前位置
# 只有一个__next__()方法
# [i*2 for i in range(10)]#########列表生成式
# (i*2 for i in range(10))#########列表生成器

import time

'''
def fib(max):############斐波那契函数
    n , a , b = 0 , 0 , 1
    while n < max:
        yield b
        a , b = b ,a + b
        n+=1

f = fib(10)
print(f.__next__())
'''


def rec(obj):
    print("prepare to recive pigs %s" % obj)
    while True:
        pig = yield
        print("把第%s个pig送给了%s" % (pig, obj))


def pro(master):
    e1 = rec("vergil")
    e1.__next__()
    for i in range(1, 99999999999999999999999999999999999999999):
        print("%s做好了第%s个pig" % (Mr_right, i))
        e1.send(i)


pro("danti")

装饰器

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author:Vergil Fu

#1.函数即变量
#2.高阶函数
#3.嵌套函数
import time
'''
#基础版
def deco(func):
    def wrap(*args,**kwargs):
        start_time = time.time()
        func()
        end_time = time.time()
        print(end_time - start_time)
        print("in the deco")
    return wrap

@deco
def func():
    time.sleep(3)
    print("in the func")
func()

@deco
def hello():
    print("in the hello".center(50, "-"))
    print("hello world!")
hello()


##等同于装饰器
def func1():
    time.sleep(3)
    print("in the func1")

def deco1(func):
    print("the %s is running!"%func)
    return func

deco1(func1)


#进阶版
mysql = {"username1":"vergil","pw1":123456,"job1":"test","balance1":20000,"age1":25,"salary1":22}

def key(func):
    def wrap(*args,**kwargs):
        username = input("username:")
        password = int(input("password:"))
        if username == mysql["username1"] and password == mysql["pw1"]:
            func()
        else:
            print("wrong message!!!")
    return wrap

@key
'''
# def info(*args,**kwargs):
#     info1 = '''
# --------info of {name}--------
# my name is {name}
# I am {age} year-old
# I earn {salary} per month'''.format(name = mysql["username1"],age = mysql["age1"],salary = mysql["salary1"])
#     print(info1)
# info()


#加强版
mysql = {"user_local":"vergil","user_ad":"admin","pw_local":123456,"pw_ad":123456}
def web(author_type):
    def wrapper(func):
        def wrapper_out(*args,**kwargs):
            username = input("username:")
            passwd = int(input("password:"))
            if author_type == "local":
                if username == mysql["user_local"] and passwd == mysql["pw_local"]:
                    print("hello %s"%username)
                    func()
                else:
                    print("invalid input")
            else:
                if username == mysql["user_ad"] and passwd == mysql["pw_ad"]:
                    print("hello %s"%username)
                    func()
                else:
                    print("invalid input")
        return wrapper_out
    return wrapper

@web(author_type = "local")
def local():
    print("welcome local guest!!!".center(50,"-"))

@web(author_type = "administrator")
def admin():
    print("welcome administrator!!!".center(50,"-"))



local()
admin()

迭代器

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author:Vergil Fu

#迭代器:可以用for循环,可以调用next方法
#生成器一定是迭代器,迭代器不一定是生成器

from collections import Iterator

a = (i for i in range(0,10))
b = [1,2,3]
c = "123"
d = {"a":1,"b":2,"c":3}

print(isinstance(a,Iterator))
print(isinstance(b,Iterator))
print(isinstance(c,Iterator))
print(isinstance(d,Iterator))
print(isinstance(iter(b),Iterator))
print(isinstance(iter(c),Iterator))
print(isinstance(iter(d),Iterator))

it = iter([1,2.3])
while True:
    try:
        x = next(it)
    except StopIteration:
        break

 导入模块

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author:Vergil Fu
'''
1、定义:
    模块:用来从逻辑上组织python代码(变量、函数、类、逻辑:实现一个功能),本质上就是py结尾的文件(文件名123.py,模块名123)
    包:用来从逻辑上组织模块的,本质上就是一个文件夹/目录(带一个__init__.py文件)
2、导入方法:
    import 123
    import 123,456
    from 123 import *   ################################效率更高
    from 123 import func1,func2,func3###################效率更高
    from 123 import func as func_123####################效率更高
3、import本质(路径搜索和搜索路径):
    导入模块的本质就是把python文件解释一遍
    导入包就是执行包里面的__init__.py文件
4、模块的分类:
    标准库
    开源模块
    自定义模块
'''
###导入模组
import sys,os

x=os.path.dirname(os.path.dirname((os.path.dirname(os.path.abspath(__file__)))))#################取出路径
sys.path.append(x)###############################################################################添加路径
import module
module.produce("Alex")###########################################################################调用模组

###导入包下面的模组
sys.path.append(r"C:\Users\Administrator\PycharmProjects\untitled3\lia\笔记\5\module_test")######添加路径
import module_test.module_test1
module_test.module_test1.module_test1_func()#####################################################调用模组

###导入别的路径模组
sys.path.append(os.path.dirname(os.path.dirname(__file__)))######################################添加路径
from mod import mod1
mod1.mod1_func()#################################################################################调用模组

from module_test import *  #####################################################################导入整个包
module_test1.module_test1_func()

from mod2 import func2##########################################################################导入模组特定的函数
func2()###########################################################################################直接调用函数

random

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author:Vergil Fu
import random
print(random.random())############################[0,1),小数
print(random.uniform(1,10))#######################[1,10),小数
print(random.randint(1,10))#######################[1,10],正数
print(random.randrange(1,10))#####################[1,10),正数
print(random.sample("vergil",2))##################从样本中随机取2位

a = [1,2,3,4,5,6]
random.shuffle(a)##############打乱列表顺序
print(a)

###运用场景
#验证码
s = "skajflksdjlfsjaf"
a = ""

for i in range(1,5):
    a += str(random.sample(s,1))
print(a)


b = ""
for i in range(1,5):
    b += str(random.randint(1,9))
print(b)


c = ""
for i in range(1,5):
    sample = random.randint(65,90)
    c += chr(sample)######################################对应ASCII码
print(c)


count = 1
d = ""
while count < 5:
    i = random.randint(48,90)
    if i > 57 and i < 65:
        pass
    else:
        d += chr(i)
        count += 1
print(d)


e = ""
for i in range(1,5):
    r = random.randint(1,4)
    if i == r:
        e += chr(random.randint(65,90))
    else:
        e += chr(random.randint(48,57))
print(e)

time

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author:Vergil Fu

#时间戳
import time
print(time.time())################################################从1970年开始,获取时间戳
print(time.mktime(time.localtime()))##############################从元组转化为时间戳

#元组
import tables
print(time.localtime())###########################################拆成9个元素的元组,UTC+8
print(time.gmtime(time.time()))###################################从时间戳转化为元组
print(time.strptime("2021-11-06 21:58:01","%Y-%m-%d %H:%M:%S"))###从格式化字符串转化为元组

x = time.localtime()
print(x.tm_year)

#字符串
print(time.strftime("%a %A %b %B %c %I     %Y-%m-%d %H:%M:%S"))############转化为格式化字符串

#标准化时间
print(time.asctime(time.localtime()))######################################从元组转化为标准时间
print(time.ctime(time.time()))#############################################从时间戳转化为标准时间

#datetime
import datetime
print(datetime.datetime.now())#############################################获取现在的时间
print(datetime.datetime.now()+datetime.timedelta(-3))######################获取3天前的时间
print(datetime.datetime.now()+datetime.timedelta(minutes=-3))##############获取3分钟之前的时间
print(datetime.datetime.now()+datetime.timedelta(hours=-3))################获取3小时前的时间
print(datetime.date.fromtimestamp(time.time()))############################从时间戳转化为2021-11-06

正则表达式

import re
res = re.match("fu\d+","fu321654shiwei1231654")#######################匹配fu和后面多个数字
print(res)
print(res.group())
res = re.match(".","fu321654shiwei1231654")############################匹配任意字符
print(res.group())
res = re.search("s[a-z]+i","fu321654shiwei1231654")####################匹配shiwei
print(res.group())
res = re.search("s[a-zA-Z]+i","fu321654shiweiShiwei1231654")###########匹配大小写
print(res.group())
res = re.search("s.+i","fu321654shiweiShiwei1231654")##################全匹配
print(res.group())
res = re.search("weiS?","fu321654shiweiShiwei1231654")#################S匹配一次,如果没有就不匹配S
print(res.group())
res = re.findall("[1-9]{1,3}","fu654shiweiShiwei54")##################匹配所有1-3个的数字
print(res)
res = re.findall("[1-9]{3}","fu651233214123shiweiShiwei54")###########匹配所有1-3个的数字
print(res)
res = re.findall("shi|Shi","fu651233214123shiweiShiwei54")############匹配shi或Shi
print(res)
res = re.search("(shiwei){2}(\|\|=){2}","fushiweishiwei||=||=")#######分组查询
print(res.group())
res = re.search("\s+","\t\n\r")#######################################匹配换行符
print(res)
res = re.search("(?P<name>[a-zA-Z]+)(?P<id>[0-9]+)","vergil157215961")#转化为字典
print(res.groupdict())
print(res.groupdict()["name"])
print(res.group("id"))
res = re.split("[0-9]+","sa23f1s32f132sa1f32sd1")#####################按数字来拆分
print(res)
res = re.sub("[0-9]+","|","sad32f13s21f32sa1",count=3)################用|代替数字3次
print(res)
res = re.search("[a-z0-9]+","sadASDF13s21f32sa1",flags=re.I)##########无视大小写
print(res.group())
res = re.match(".+","\n\rfu321654shiwei1231654",flags=re.S)###########无视换行符
print(res.group())


'''
^a     判断是否以a开头
$a     判断是否以a结尾
\d     匹配数字
\D     匹配非数字
\w     匹配[a-z][A-Z][0-9]
\W     匹配非[a-z][A-Z][0-9]
s      匹配空白字符
'''

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值