[百度飞桨领航团]零基础Python学习笔记


一、 python入门

1.执行python代码

windows:win+R+cmd
python 文件路径

2.基本数据类型

整数、浮点数(1.58e10=1.5*10^10)、字符串(‘ ’,” ”)、布尔值(True、False)、空值(None)
运算符

3.变量赋值

number=1
name=’python’
answer=True
number+=1
注意:无i++
起名规则和C语言类似

4.数据类型间相互转换

int()
str()
bool()
float()

5.组合数据类型

列表 list
list是一种有序的集合,可以随时添加和删除其中的元素

list1 = [1, 2, 3, 4, 5 ]
list2 = ["a", "b", "c", "d","e","f"]
list3 = ['physics', 'chemistry', 1997, 2000]

len(list1)

list1[4]					#索引
list3.append(5)				#最后添加
list1.pop()					#删除并弹射

元组 tuple
另一种有序列表叫元组:tuple。tuple和list非常类似,但是tuple一旦初始化就不能修改

tuple1 = (1, 2, 3, 4, 5 )
tuple2 = ("a", "b", "c", "d","e","f")
tuple3 = ('physics', 'chemistry', 1997, 2000)

字典dict
Python内置了字典:dict的支持,dict全称dictionary,在其他语言中也称为map,使用键-值(key-value)存储,具有极快的查找速度。

word = {'apple':'苹果','banana':'香蕉'}
scores = {'小张':100, '小李':80}
grad = {4:'很好',3: '好',2:'中',1:'差',0:'很差'}
scores['小张']						#通过key访问value

集合 set
set和dict类似,也是一组key的集合,但不存储value。由于key不能重复,所以,在set中,没有重复的key。

6.流程控制

break continue pass

二、编程基础

1.字符串索引、切片

string = 'Hello world!'
string[2]
string[2:5]
string[3:]
string[8:2:-1]

for s in string:
    print(s)

# 如果字符串以'pr'结尾,则打印
list_string = ['apple','banana_pr','orange','cherry_pr']
for fruit in list_string:
    if fruit.endswith('pr'):
        print(fruit)

2.常用函数

count 计数功能
显示自定字符在字符串当中的个数
find 查找功能
返回从左第一个指定字符的索引,找不到返回-1
index 查找
返回从左第一个指定字符的索引,找不到报错
split 字符串的拆分
按照指定的内容进行分割
replace字符串的替换
从左到右替换指定的元素,可以指定替换的个数,默认全部替换
strip字符串标准化
默认去除两边的空格、换行符之类的,去除内容可以指定

3.字符串的格式化输出


通过代码来看

name = 'CSDN'
height = 100
weight= 95
#%
print('大家好!我叫%s,我的身高是%d cm, 体重%.2f分' % (name, hight, weight))
#format
print('大家好!我叫{},我的身高是{:d} cm, 体重{:.2f}分'.format(name, int(hight), weigh))
#f-string
print(f"大家好!我叫{name},我的身高是{hight:.3f} cm, 体重{weight}")

4.列表生成式

list_1 = [1,2,3,4,5]
[n for n in list_1 if n%2==0]

# 字符串中所有以'sv'结尾的
list_2 = ['a','b','c_sv','d','e_sv']
[s for s in list_2 if s.endswith('sv')

# 取两个list的交集
list_A = [1,3,6,7,32,65,12]
list_B = [2,6,3,5,12]
[i for i in list_A if i in list_B]

5.异常与错误处理

try:
<语句>        #运行别的代码
except <名字><语句>        #如果在try部份引发了'名字'异常
except <名字><数据>:
<语句>        #如果引发了'名字'异常,获得附加的数据
else:
<语句>        #如果没有异常发生
finally:
<语句>        #有没有异常都会执行

三、 函数基础

函数代码块以 def 关键词开头,后接函数标识符名称和圆括号()。
任何传入参数和自变量必须放在圆括号中间。圆括号之间可以用于定义参数。
函数的第一行语句可以选择性地使用文档字符串—用于存放函数说明。
函数内容以冒号起始,并且缩进。
return [表达式] 结束函数,选择性地返回一个值给调用方。不带表达式的return相当于返回 None。

1.参数传递

位置参数
位置参数是最简单的一种函数调用的方式。位置参数须以正确的顺序传入函数、数量必须和声明时的一样。
缺省参数
调用函数时,缺省参数的值如果没有传入,则被认为是默认值。
可变参数
顾名思义,可变参数就是传入的参数个数是可变的,可以是1个、2个到任意个,还可以是0个。
关键字参数
关键字参数允许你传入0个或任意个含参数名的参数,这些关键字参数在函数内部自动组装为一个dict。
命名关键字参数
如果要限制关键字参数的名字,就可以用命名关键字参数

2.变量的作用域和global变量

局部变量作用域在函数内

全局变量作用域在函数外(gobal)

函数优先使用局部变量,在没有局部变量的情况下使用全局变量

3.lambda匿名函数

# 加法运算 接受两个参数,返回参数之和
add = lambda arg1, arg2: arg1 + arg2
add(1,2)

4.map / reduce/sorted

map: 接收两个参数,一个是函数,一个是Iterable,map将传入的函数依次作用到序列的每个元素,并把结果作为新的Iterator返回。

reduce: 用传给 reduce 中的函数 function(有两个参数)先对集合中的第 1、2 个元素进行操作,得到的结果再与第三个数据用 function 函数运算,依此类推,最后得到一个结果。

sorted: 排序函数

sorted([36, 5, -12, 9, -21])
sorted([36, 5, -12, 9, -21], reverse=True)

points = [(5,2), (7,3), (3,4),(1,1),(2,6)] 
#按x坐标排序
f_x = lambda x:x[0]
sorted(points, key=f_x)

四、面向对象

这里通过作业来回忆
要求:定义Student类,包括name、dob、age、gender和score属性,包括top3方法用来返回学生的最大的3个成绩(可重复)、sanitize方法用来将负的分数变为正的分数,负的分数可能是输入错误。声明stu_list对象组数用于存储所有的学生对象。最后输出所有的学生信息包括姓名、生日、年龄、性别、最高的3个分数。

def get_coach_data(filename):
    with open(filename) as f:
        line = f.readline()
    return line.strip().split(',')

class Student():
    def __init__(self,a_name,a_birth,a_age,a_sex,a_score=[]):
        self.name=a_name
        self.birth=a_birth
        self.age=a_age
        self.sex=a_sex
        self.score=a_score

    def top3(self):
        return sorted(set([self.sanitize(s) for s in self.score]),reverse=True)[0:3]
    
    def sanitize(self,score_string):
        return abs(int(score_string))

stu1=get_coach_data('work/stu1.txt')
stu_1=Student(stu1.pop(0),stu1.pop(0),stu1.pop(0),stu1.pop(0),stu1)
stu2=get_coach_data('work/stu2.txt')
stu_2=Student(stu2.pop(0),stu2.pop(0),stu2.pop(0),stu2.pop(0),stu2)
stu3=get_coach_data('work/stu3.txt')
stu_3=Student(stu3.pop(0),stu3.pop(0),stu3.pop(0),stu3.pop(0),stu3)
stu4=get_coach_data('work/stu4.txt')
stu_4=Student(stu4.pop(0),stu4.pop(0),stu4.pop(0),stu4.pop(0),stu4)

def print_student(stu):
    print('姓名:%s 生日:%s 年龄:%s 性别:%s 分数:%s' %(stu.name,stu.birth,stu.age,stu.sex,stu.top3()))

print_student(stu_1)
print_student(stu_2)
print_student(stu_3)
print_student(stu_4)

要求:定义Spostudent、Artstudent为Student的子类,在子类的属性里面新增了spe为特长分数。Spostudent包括的top3方法返回的是最低的3个得分(可重复),Artstudent包括top3方法返回的是最高的3个得分(可重复),最后使用多态的方式输出2个特长同学的姓名、生日、年龄、性别、分数、特长分。

def get_coach_data(filename):
    with open(filename) as f:
        line = f.readline()
    return line.strip().split(',')

class Spostudent(Student):
    def __init__(self,a_name,a_birth,a_age,a_sex,a_spe,a_score=[]):
        Student.__init__(self,a_name,a_birth,a_age,a_sex,a_score)
        self.spe=a_spe

    def top3(self):
        return sorted([self.sanitize(s) for s in self.score])[0:3]

class Artstudent(Student):
    def __init__(self,a_name,a_birth,a_age,a_sex,a_spe,a_score=[]):
        Student.__init__(self,a_name,a_birth,a_age,a_sex,a_score)
        self.spe=a_spe

    def top3(self):
        return sorted([self.sanitize(s) for s in self.score],reverse=True)[0:3]

stu5=get_coach_data('work/stu5.txt')
stu_5=Spostudent(stu5.pop(0),stu5.pop(0),stu5.pop(0),stu5.pop(0),stu5.pop(0),stu5)
stu6=get_coach_data('work/stu6.txt')
stu_6=Artstudent(stu6.pop(0),stu6.pop(0),stu6.pop(0),stu6.pop(0),stu6.pop(0),stu6)

def print_student(stu):
    print('姓名:%s 生日:%s 年龄:%s 性别:%s 分数:%s 特长分:%s' %(stu.name,stu.birth,stu.age,stu.sex,stu.top3(),stu.spe))

print_student(stu_5)
print_student(stu_6)

在这里要注意父类对象__init__中a_score不能再声明一个空的

五、文件操作与常用模块的使用

这里掌握的不是很好,具体参看网上内容

总结

通过学习,掌握了python的基础知识,还需继续学习其他内容。
课程链接:https://aistudio.baidu.com/aistudio/course/introduce/7073

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值