《Python基础教程(第三版)》阅读笔记暨Python3入门基础教程

版权声明:本文为博主原创文章,未经博主允许不得转载。文章中有连接失效或是技术谬误的地方,请与我联系。 https://blog.csdn.net/luchengtao11/article/details/82660473

第一章、快速上手:基础知识

'''
第一章:基础知识
1、python无需加分号,加了也无所谓
2、Python / 除法的结果为浮点数,如果想要整除则要使用//,整除会向下取整,也就是:
    10//-3  ==-4
3、Python3中,所有的字符串都是Unicode字符串
'''
# 幂运算
2**4

'''
# 获取用户输入
x=input("x:") #此时x为字符串
y=input("y:") 
print(int(x)*int(y))
'''
# 可使用变量来引用函数

import math
foo=math.sqrt
print(foo(9))

#原始字符串,会在字符串中包含任何字符,原始字符串的最后一个字符不能是反斜杠
print(r"C:\nowhere") 

#字符串的编码
#最好使用UTF-8,实际上它也是默认的编码
"Hello,World!".encode("ASCII")
"Hello,World!".encode("UTF-8")
"Hello,World!".encode("UTF-32")

'''
函数速查:
pow(a,b)            幂运算
abs()               绝对值
round()             圆整到最接近的整数,并在两个整数一样接近时圆整到偶数,相当于四舍五入
math.floor()        向下取整,要import math
math.ceil()         向上取整
sqrt()              计算平方根 需要from math import sqrt
'''

第二章、列表和元组

1、列表是可以修改的,而元组不可以

2、列表的访问方式:

numbers=[1,2,3,4,5,6,7,8,9,10]
print(numbers[5])               #索引 结果为6
print(numbers[3:-3])            #切片 结果为[4,5,6,7]
print(numbers[1:9:2])           #以步长为2进行提取 结果为[2,4,6,8]
print(numbers[5:1:-1])          #从右往左提取元素,结果为[6,5,4,3]

3、列表具有加法和乘法,

>>> 'python' * 5
'pythonpythonpythonpythonpython'
>>> [42] * 10
[42, 42, 42, 42, 42, 42, 42, 42, 42, 42]

4、成员资格

使用运算符in可以判断某元素是否在某列表里,返回结果为布尔值

>>> permissions = 'rw'
>>> 'w' in permissions
True

database = [
['albert', '1234'],
['dilbert', '4242'],
['smith', '7524'],
['jones', '9843']
]

username="jones"
pin="9843"
if [username, pin] in database: print('Access granted')

5、内置函数len、max、min可以获取列表的长度、最大值、最小值

6、删除元素

>>> names = ['Alice', 'Beth', 'Cecil', 'Dee-Dee', 'Earl']
>>> del names[2]
>>> names
['Alice', 'Beth', 'Dee-Dee', 'Earl']

7、给切片赋值

通过切片赋值的方式可以替换为长度与其不同的序列

>>> name = list('Perl')
>>> name[1:] = list('ython')
>>> name
['P', 'y', 't', 'h', 'o', 'n']

通过切片还可以在不替换原有元素的情况下插入新元素

>>> numbers = [1, 5]
>>> numbers[1:1] = [2, 3, 4]
>>> numbers
[1, 2, 3, 4, 5]

8、列表方法

append()     #在列表末尾添加对象
extend()     #同时将多个对象附加到列表末尾
clear()      #清空列表的内容
count()      #计算指定元素在列表中出现了多少次
index()      #在列表中查找指定值第一次出现的索引
insert()     #将一个对象插入列表
pop()        #从末尾删除一个元素并返回这个元素
remove()     #删除第一个为指定值的元素,注意,如果不存在指定的元素,将会报错
>>> x = ['to', 'be', 'or', 'not', 'to', 'be']
>>> x.remove('be')
>>> x
['to', 'or', 'not', 'to', 'be']

reverse()    #倒序
sort()       #排序 两者都只是修改列表,但返回None

#其他
list(seq)    #将序列转换为列表
tuple(seq)   #将序列转换为元组

第三章、使用字符串

1、字符串的基本操作

所有标准序列操作都适用于字符串,但是字符串是不可变的,所以所有的元素赋值和切片赋值都是非法的

2、超精简版的设置字符串的格式

>>> "{3} {0} {2} {1} {3} {0}".format("be", "not", "or", "to")
'to be or not to be'

3、字符串方法

center() #通过在两边添加填充字符(默认为空格)让字符串居中
>>> "The Middle by Jimmy Eat World".center(39, "*")
'*****The Middle by Jimmy Eat World*****'
find     #在字符串中查找子串,如果找到则返回第一个字符的索引,否则返回-1
#相关方法:rfind、 index、 rindex、 count、 startswith、 endswith



join    #其作用与split相反,用于合并序列的元素
>>> dirs = '', 'usr', 'bin', 'env'
>>> '/'.join(dirs)
'/usr/bin/env

lower    #返回字符串的小写版本
replace    #将指定子串都替换为另一个字符串,并返回替换后的结果
>>>'This is a test'.replace('is', 'eez')
'Theez eez a test'


split    #与join相反,用于将字符串拆分为序列
>>> '/usr/bin/env'.split('/')
['', 'usr', 'bin', 'env']

strip    #将字符串开头和末尾的空白删除,并返回删除后的结果。还可以指定删除那些字符
>>> '*** SPAM * for * everyone!!! ***'.strip(' *!')
'SPAM * for * everyone'


#判断字符串是否满足特定的条件
isalnum、 isalpha、 isdecimal、 isdigit、 isidentifier、 islower、 isnumeric、
isprintable、 isspace、 istitle、 isupper

第四章、当索引行不通时

1、创建和使用字典

phonebook = {'Alice': '2341', 'Beth': '9102', 'Cecil': '3258'}

2、函数dict

从其他映射或键值对序列创建字典

>>> items = [('name', 'Gumby'), ('age', 42)]
>>> d = dict(items)
>>> d
{'age': 42, 'name': 'Gumby'}
>>> d['name']
'Gumby'

3、字典方法

clear             #删除所有的字典项,所有指向同一个字典的变量都将为空
copy              #返回一个新字典,但是这个方法执行的是浅拷贝

from copy import deepcopy
dc = deepcopy(d)    #深拷贝


fromkeys         #创建一个新字典,其中包含指定的键,且每个键对应的值都是None
get              #根据键来获取值,如果不存在则返回None,比[]更安全
pop              #根据指定键删除键值对
popitem          #随机地弹出一个字典项




第五章、条件、循环及其他语句

1、python缩进标准也是最佳的做法是只使用空格(而不使用制表符),且每级缩进4个空格。

2、==用来检查两个对象是否相等,而is用来检查两个对象是否相同

3、pass 什么都不做,del 删除对象,exec用于将字符串作为python程序执行,函数eval计算用字符串表达的表达式并返回结果。

第六章、抽象

1、带*号的参数用于收集剩下的参数

def print_params_2(title, *params):
print(title)
print(params)

>>> print_params_2('Params:', 1, 2, 3)
Params:
(1, 2, 3)

第七章、再谈抽象

1、要让方法或属性成为私有的,只需让其名称以两个下划线打头即可

2、Python分为类属性和实例属性,类属性在__init__()外初始化,相当于C++中的静态成员变量。实例属性相当于C++的成员变量。

3、抽象基类

from abc import ABC, abstractmethod
class Talker(ABC):
@abstractmethod
def talk(self):
pass

第八章、异常

1、捕获异常

try:
x = int(input('Enter the first number: '))
y = int(input('Enter the second number: '))
print(x / y)
except ZeroDivisionError:
print("The second number can't be zero!")

第九章、魔法方法、特性和迭代器

猜你喜欢

转载自blog.csdn.net/luchengtao11/article/details/82660473