python基础

常用逻辑运算符

and 、or、not

列表操作

访问列表

hero = ["猴子","妲己","鲁班","亚瑟","蔡文姬"]
print(info[2])   #访问列表

插值语法

hero = ["猴子","妲己","鲁班","亚瑟","蔡文姬"]
print(f'打野英雄-{hero[0]}')   #插值语法

修改列表

hero = ["猴子","妲己","鲁班","亚瑟","蔡文姬"]
hero[2] = '后羿'   #修改列表

在列表中添加元素

hero = ["猴子","妲己","鲁班","亚瑟","蔡文姬"]
hero.append("鬼谷子")

列表插值

hero = ["猴子","妲己","鲁班","亚瑟","蔡文姬"]
hero.insert(1,"李白")

根据索引删除列表值

hero = ["猴子","妲己","鲁班","亚瑟","蔡文姬"]
del hero[0]

根据值删除列表元素

hero = ["猴子","妲己","鲁班","亚瑟","蔡文姬"]
hero.remove('鲁班')

弹出列表值(只能根据索引弹出)

hero = ["猴子","妲己","鲁班","亚瑟","蔡文姬"]
hero.pop(0)

获取长度

hero = ["猴子","妲己","鲁班","亚瑟","蔡文姬"]
print(len(hero))

获取索引

hero = ["猴子","妲己","鲁班","亚瑟","蔡文姬"]
print(hero.index('蔡文姬'))

for

简单语法

number = [1,2,3,4,5,6,7,8,9]
for item in number:
    if item%2 ==0:
        continue  #跳过满足条件的数
    else:
        print(item)

遍历切片

hero = ["猴子","妲己","鲁班","亚瑟","蔡文姬"]
for item in hero[0:3]:    #到鲁班位置
    print(item)

range生成数

number =  list(range(1,6))  #生成1~5的数,转化为列表
even = list(range(2,11,2))  #生成2~11的偶数

深拷贝

info = "33"
info2 = info[:]

元组

#元组不可被修改,只能重新复制,可遍历
info = (200,50,300) 

if elif else

一次性的条件

age = 15
if age < 4:
    print("门票免费")
elif age < 18:
    print("门票半价")
else:
    print("门票全价")

多个条件

hero = ["猴子","妲己","鲁班","亚瑟","蔡文姬"]
if '妲己' in hero:
    print("法师英雄")
if '亚瑟' in hero:
    print('对抗路')

字典

访问字典

hero = {"打野":"李白","法师":"貂蝉","输出":"后羿"}
print(f"选中英雄{hero['法师']}")

添加字典

hero = {"打野":"李白","法师":"貂蝉","输出":"后羿"}
hero['上路'] = "亚瑟"

删除键值对

hero = {"打野":"李白","法师":"貂蝉","输出":"后羿"}
del hero['法师']

get访问值

hero = {"打野":"李白","法师":"貂蝉","输出":"后羿"}
print(hero.get("辅助",'none'))

遍历字典

hero = {"打野":"李白","法师":"貂蝉","输出":"后羿"}
#for key in hero.keys():
#for value in hero.values():
for key,value in hero.items():
    print(f"我方{key}是{value}")

嵌套

animal01 = {"name":"大熊猫","postrue":"黑白相间"}
animal02 = {"name":"华南虎","postrue":"猛兽"}
animal03 = {"name":"平头哥","postrue":"不服就干"}
info = [animal01,animal02,animal03]
for item in info:
    print(f"{item['name']}的印象是{item['postrue']}")

获取用户输入值(值为字符)

age = input("你多大了:")
if(int(age)<18):
    print("少年")
if(int(age)<60 and int(age)>18):
    print("中年")
else:
    print("老年")

while循环

语法

number = 0
while number<=10:
    print(number)
    number += 1
    if number == 6:
        break

使用标志退出

bool = True
while bool:
    print("")
    info = input("输入数字:")
    if info == '9':
        bool = False
    else:
        print(f"你的输入是{info}")

函数

参数可选

def name(v1,v2,v3=""):
    if v3 !='':
        name = f'{v1}{v2}{v3}'
    else:
        name = f'{v1}{v2}'
    return name

压缩法

list01 = ["唐生","猴子","沙僧"]
list02 = [101,102,103]
def zip(list01,list02):
    for item in range(len(list01)):
        yield (list01[item],list02[item])  #用索引提取到的数据进行拼接
for item in zip(list01,list02):
    print(item)

函数编程思想
hero.py

class Cls:
    @staticmethod
    def max_gongj(list,lambd):
        frist = list[0]
        for i in range(1,len(list)):
            if lambd(frist) < lambd(list[i]):
                frist = list[i]
        return frist
class Info:
    def __init__(self,name='',gongj=0):
        self.name = name
        self.gongj = gongj
from hero import Info,Cls as slc  
hero = [Info("妲己",200),Info("小乔",700),Info("八戒",600),Info("李白",1200)]
print(f'攻击力最强英雄{slc.max_gongj(hero,lambda v:v.gongj).name}')

装饰器

def zhuangsh(res):
    def zhuang(*args,**kwargs):
        print("函数名:",res.__name__)  #新功能
        res(*args,**kwargs)     #调用原功能  *接收多个位字实参 **接收关键字实参
    return zhuang

@zhuangsh  #使用装饰器
def res01():
    print("res01执行\n")

集合

set18 = {1,2,3}
set09 = {2,3,4}
#--交集(两边都有)
print(set18 & set09) #{2, 3}

#--并集
print(set18 | set09) #{1, 2, 3, 4}

#--补集(两边都没有的)
print(set18 ^ set09) #{1, 4}
print(set18 - set09) #{1}   set18有set19没有
print(set09 - set18) #{4}

迭代器

dict = {"打野":"韩信","法师":"露娜","复制":"蔡文姬","对抗路":"赵云"}
dicts = dict.__iter__()  #生成迭代器
while True:
    #迭代完后会出现停止迭代的异常(StopIteration)
    try:
        dicte = dicts.__next__()  #进行迭代
        print(f"{dicte}对应英雄{dict[dicte]}")
    except StopIteration:
        break

类的设计原则

class HeroInfo:  #数据模型
    def __init__(self,name='',gongj=0):
        self.name = name
        self.gongj = gongj
class HeroList:  #逻辑控制
    def __init__(self):
        self.__list = []  #私有化对类外不可用
    def list(self):  #私有化公开
        return self.__list
    def addhero(self,info):
        self.__list.append(info)
class Operation_Hero:  #视图
    def __init__(self):
        self.__hero = HeroList()
    def gethero(self):
        name = input("英雄:")
        gongj = self.input_type("攻击力:")
        info = HeroInfo(name,gongj)
        self.__hero.addhero(info)  #在函数内部添加信息一对一,不会创建新列表
    def to_view(self):
        for item in self.__hero.list():
            print(f"{item.name}的攻击力{item.gongj}")
    def input_type(self,values):
        while True:
            try:
                return int(input(values))
            except:
                print("输入错误!!!")
hero = Operation_Hero()
hero.gethero()
hero.to_view()

类的使用方法

class Demo:
    def __init__(self,name='',age=0):
        self.name = name
        self.age = age
    def __str__(self):
        return "name:%s-age:%d"%(self.name,self.age)
    @staticmethod  #静态方法(可以不用实例化而调用)
    def show_name():
        print("体迅飞凫")
    number = 0
    @classmethod #类方法(可以使用全局变量)
    def leij(cls):
        cls.number += 1
print(Demo("妲己",23))
Demo.leij()
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值