python基础整理一

勤奋不是嘴上说说而已,而是实际的行动,在勤奋的苦度中持之以恒,永不退却。业精于勤,荒于嬉;行成于思,毁于随。在人生的仕途上,我们毫不迟疑地选择勤奋,她是几乎于世界上一切成就的催产婆。只要我们拥着勤奋去思考,拥着勤奋的手去耕耘,用抱勤奋的心去对待工作,浪迹红尘而坚韧不拔,那么,我们的生命就会绽放火花,让人生的时光更加的闪亮而精彩。

导读:本篇文章讲解 python基础整理一,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com,来源:原文

python的特性

1.python语法简单,容易理解,容易学习
2.跨平台,可以在windows,linux,mac os
3.可以做网站、爬虫、大数据处理
4.拥有强大的第三方库numpy,panda...

python 之禅

输入import this
>>>import this
The Zen of Python, by Tim Peters
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
python之禅 翻译 备注
The Zen of Python, by Tim Peters 作者:Tim Peters
Beautiful is better than ugly. 优美胜于丑陋 python以编写优美的代码为目标
Explicit is better than implicit. 明了胜于晦涩 优美的代码应当是明了的,命名规范,风格相似
Simple is better than complex. 简洁胜于复杂 优美的代码应当是简洁的,不要有复杂的内部实现
Complex is better than complicated. 复杂胜于凌乱 如果复杂是不可避免的,代码也要保持接口的简洁
Flat is better than nested. 扁平胜于嵌套 优美的代码应当是扁平的不要有过多的嵌套
Sparse is better than dense. 间隔胜于紧凑 优美的代码应该具有适当的间隔,不要奢望一行代码解决问题
Readability counts. 可读性很重要 优美的代码是可读的
Special cases aren’t special enough to break the rules.Although practicality beats purity. 即便假借特例的使用之名,也不可违背这些规则
Errors should never pass silently.
Unless explicitly silenced. 不要包容所有的错误除非你确定要这么做 精确的捕获异常,不要编写except: pass风格的代码
In the face of ambiguity, refuse the temptation to guess. There should be one– and preferably only one –obvious way to do it. 当存在多种可能,不要尝试去猜测,而是尽量找一种,最好是唯一一种的明显的解决方案 如果不确定就用穷举的办法
Although that way may not be obvious at first unless you’re Dutch. 虽然这并不容易,因为你不是dutch dutch这里指的是python之父
Now is better than never. Although never is often better than right now. 做总比不做好,但是不假思索的做还不如不做
If the implementation is hard to explain, it’s a bad idea. 如果你的解决方案很难描述,则肯定不是一个好方案
If the implementation is easy to explain, it may be a good idea. 易于描述的方案很可能是一个好的方案
Namespaces are one honking great idea – let’s do more of those! 命名空间是一个很好的解决方案,我们需要多加利用

hello world

print('hello world')
hello world
print("hello world")
hello world
print("\"hello world\"")
"hello world"
print('\'hello world\'')
'hello world'
#合理的使用单双引号可以避免使用转义字符
print("'hello world'")
'hello world'
print('"hello world"')
"hello world"

python可以直接当作计算器来使用

2+3
5
2-1
1
2*3
6
2*3
6
5%2
1
#2的3次方
2**3
8
#8开3次方
8**(1/3)
2.0

import math
#math.pi是180°,math.pi/2是90°
math.sin(math.pi/2)
math.sin(math.pi/3)
#向下取整,输出9
math.floor(9.599)
#向上取整,输出10
math.ceil(9.599)
#非math,四舍五入
round(9.4)
9
round(9.5)
10

#format函数,增强的字符串格式化函数
a=5
b=6
"a的值为:{},b的值为:{}".format(a,b)
'a的值为:5,b的值为:6'

变量:代表某个值的名称

#语法糖
a=10
b=20
a,b=b,a
#变量的命名规范
1.标识符的第一个字符必须是字母表中的字母(大写或小写)或者一个下划线
2.标识符的其他部分可以由字母,下划线和数字组成
3.标识符对大小写敏感
总结:首字母不能是数字,标识符之间不能有空格,‘-

代码规范

1.不要使用单字符
2.变量名能清晰表达变量意思
3.合理使用字母中间下划线

变量类型

变量类型 标识符
字符串 str
数字 int, float,complex(复数)
列表 list
元组 tuple
字典 dict
布尔 boolean (True, False)
line="hello"
id(line)
1733427178992
line="hello world"
id(line)
1733990190576
#取前20个字符,每隔一个取一个,一共是10个字符
line[0:20:2]
#取后10个字符
line[-10:]
#反转字符
line[::-1]
String是不可变字符
line[0]='a'会出错误
str函数 含义
capitalize() 返回字符串第一个字符大写,其他小写的字符串
center() line.center(30)’ hello world, I am coming! ’ line.center(30,’%’) ‘%%hello world, I am coming!%%%’
count() 计数函数,count(‘a’) ‘a’在字符串中出现的次数
startswith()/endswith 字符串首尾判断函数,返回为True/False
find() 返回传递参数在字符串中出现的下标,如果不存在返回-1,find(‘a’,1)从第二个字符开始查找
index() 功能和find()相同,不同是如果不存在返回一个error
upper() 所有字符大写
lower 所有字符小写
istitle/isUpper, isLower 是否标题,是否大写,是否小写
strip()/rstrip/lstrip 取得有效的字符,剔除空格,tab,换行等等
swapcase 大小写转换
+ 字符串加法
* line*3
len() 返回字符串的长度
id 返回字符串的地址

字符串是不可变类型的,不可以进行赋值操作修改单个字符

python是动态类型语言,一个变量是什么类型,要看在程序运行过程中变量所代表的值是什么

常用函数 意义
type 查看变量类型
id 查看内存地址
isinstance(变量名,类型) 查看变量类型是否和预期类型一致,返回boolean值

列表

【重点】列表是可变类型的

列表和字符串具有相同的字符串操作

#空列表
varibals=[]
varibals=list()
可以容纳任意类型的对象,任意数量的对象
varibals=[1, 2, 3, 'nihao' , 'hello', [], [10,20]]

列表专有的方法

函数 意义
append 给列表增加一个元素,没有返回值,而是修改列表本身
insert insert(位置,插入)在位置上插入
clear 清空列表
copy 复制列表
extend a.extend(b)把列表b拼接到a后边
pop 最末尾的值弹出,pop(位置)没有位置的时候默认是最后一个,如果指定位置就弹出指定位置的值
remove 移除,remove(值)找到的第一个的值移除
sort sort()排序,sort(reverse=True)排序反转
in value in 列表

复制copy与赋值=的区别

赋值是操作的同一个对象,copy则不是
var=[1]
var_copy=var.copy()
var_2=var
var[0]=5
var_2里的值改变为5,var_copy不发生改变

序列

列表、字符串都是一个序列
列表是容器型的序列,字符串是扁平型的序列

tuple元组-当作不可变的列表

两种定义方式
var = tuple()
var =()
元组仅有两个函数,count和index

小结 元组、字符串、列表

元组 字符串 列表
t_1=[1,2,3,4,5] s_1=‘ni hao’ l_1=[1,2,3,4,5]
t_1=[5,6,7,8,9] s_1=‘how are you’ l_1=[6,7,8,9,10]
函数 元组 字符串 列表 备注
+ t_1 + t_2 s_1 + s_2 l_1 + l_2
* t_1 * 2 s_1 * 2 l_1 * 2
>< t_1 > t_2 s_1 > s_2 l_1 > l_2
[index] t_1[0] s_1[0] l_1[0] 列表可以索引赋值,元组和字符串不可以
[::] t_1[::] s_1[0:10:1] l_1[0:10:2] 列表可以切片赋值,元组和字符串不可以
len len(t_1) len(s_1) len(l_1)
bool bool( t_1) bool( s_1) bool(l_1) 空字符串、空列表、空元组转换为bool为False
count t_1.count(1) s_1.count(‘n’) l_1.count(1)
index t_1.index(1) s_1.index(‘n’) l_1.index(1)
replace 不支持 s_1.replace(‘n’,‘N’) 不支持 字符串replace返回一个新的字符串,原来的字符串不变
sort l_1.sort()
reverse l_1.reverse() 字符串不可更改,只能通过生成一个新的字符串来实现反转
append l_1.append(1)
extend l_1.extend(l_2)
remove l_1.remove(2)
pop l_1.pop()

dict字典类型

定义字典类型
var={}
var = dict()

zip()拉锁函数,把两个列表组合成列表,新的列表中的每个元素都是一个元组
words=['中','左']
locations=[100,200]
zip(words,locations)
<zip object at 0x0000020E363A5440>
list(zip(words,locations))
[('中', 100), ('左', 200)]
var2 = list(zip(words,locations))
转化为字典
dict(var2)
{'中': 100, '左': 200}
等价于dict(list(zip(words,locations)))

list(zip([1,2],[3,4],[5,6,7]))
[(1, 3, 5), (2, 4, 6)]


students=['zhang','wang','li','zhao']
dict1=dict.fromkeys(students,10)
{'zhang': 10, 'wang': 10, 'li': 10, 'zhao': 10}
函数 含义
fromkeys 初始化给定default值
get dict1(‘li’)相当于dict1.get(‘li’),区别:dict1(‘li’)值不存在返回error,get值不存在返回none,例外get如果找不到还可以指定一个值,get(‘li’,10)
keys 返回关键字列表
values 返回值列表
items 返回key和值组合的列表
pop 删除pop(‘key’)
赋值= 可以修改添加
setdefault 没有就set default,有就返回

条件判断

if condition:
  do something
elif condition: #elif可以出现0次或者多次
  do something
else:
  do something

boolean类型的运算
and or not

断言

if not condition:
  crash program

age = 10
assert age == 20, '竟然不是20岁'

循环

for 循环 - 遍历循环
while 循环-条件循环

costs=[3,4,2,1,5,6,7,9]
for cost in costs:
...     print('消费 {} 元'.format(str(cost).center(10)))

numbers=[]
while(len(numbers)<=20):
...     numbers.append(random.randint(0,10))
... print(numbers)
[9, 10, 7, 5, 10, 3, 0, 8, 7, 7, 4, 3, 10, 4, 9, 2, 0, 6, 7, 2, 9]

for i in range(20):
...     numbers.append(random.randint(0, 10))

建议

和数量有关系的时候,就用for
和数量没有关系的时候,就用while
如果在循环的过程中没有碰到break语句,就会执行else代码(循环中的else)

for循环可以构建推导式
所谓推导式就是一种从一个数据序列构建另一个数据序列的方法
非推导写法:
numbers2=[]
for i in numbers:
...     numbers2.append(i*10)
...     
numbers2
[0, 10, 20, 30, 40, 50, 60, 70, 80, 90]

推导式写法:
列表推导式
numbers3=[i*10 for i in numbers]
numbers3
[0, 10, 20, 30, 40, 50, 60, 70, 80, 90]
字典推导式
dict={i:i*10 for i in numbers}
dict
{0: 0, 1: 10, 2: 20, 3: 30, 4: 40, 5: 50, 6: 60, 7: 70, 8: 80, 9: 90}
元组推导式
tuples=(i*10 for i in numbers)
tuples
<generator object <genexpr> at 0x0000020E4ED85660> 
#生成器
list(tuples)
[0, 10, 20, 30, 40, 50, 60, 70, 80, 90]

tuples=(i*10 for i in numbers)
tuple(tuples)
(0, 10, 20, 30, 40, 50, 60, 70, 80, 90)
#循环中的else
for condition:
  do something
else:
  do something

whille condition:
  do something:
else:
  do something
a=[]
b=()
type(a)
<class 'list'>
type(b)
<class 'tuple'>
type(a), type(b)
(<class 'list'>, <class 'tuple'>)

a=[1]
b=(1)
type(a), type(b)
(<class 'list'>, <class 'int'>)

a=[1]
b=(1,) #只有一个元素的元组
type(a), type(b)
(<class 'list'>, <class 'tuple'>)

a=[1,2]
b=(1,2)
type(a), type(b)
(<class 'list'>, <class 'tuple'>)

函数

函数是组织好的、可重复使用的、能够完成特定功能的代码块,它是代码块的抽象

var = {
    'a':100,
    'b':100,
    'c':200
}
var['a']
100
#如何取value==100对应的key值?
[key for key,value in var.items() if value==100]
['a', 'b']

def getkeys(var, value1):
  return [key for key, value in var.items() if value == value1]

getkeys(var,100) #位置参数
['a', 'b']
#关键字参数参数可以不按照顺序
getkeys(var={'a': 100},value1=100)#关键字参数
['a']
getkeys(value1=100, var={'a': 100})#关键字参数
['a']


传值列表其中的值会改变
def test(var):
...     var.append(100)
...     return var;
... 
var =[]
test(var)
[100]
var
[100]
不建议对可变类型在函数内更改,建议用函数返回值进行重新赋值
def test(var):
  tmp = var.copy()
  tmp.append(100)
  return tmp;
... 
#### 位置参数和关键字参数
*args是位置参数
**kwargs是关键字参数
```python
def test(name, age, *args, **kwargs):
...     print(name, age, *args, **kwargs)

test('wang',12)
wang 12
test('wang',12, 23, 'str',[24,25])
wang 12 23 str [24, 25]
dict_var={}
dict_var={}
dict_var={'weight':120, 'height':175}
test('wang',12, dict_var)
wang 12 {'weight': 120, 'height': 175}

装饰器

def test():
...     print('test') 
可以把函数赋值给一个变量
a=test
a
<function test at 0x0000020E56DBF550>
a.__name__
'test'
a() - 调用函数

传递一个函数,并返回一个函数
def test():
...     print('test') 
def fun(test):
...     return test
... 
f = fun(test)
f.__name__
'test'
调用函数
f()
test
函数可以当作函数的返回值返回

装饰器

def test():
...     return random.random()
... 
def decorator(func):
...     def wrapper(*args, **kwargs):
...         return func(*args, **kwargs)
...     return wrapper
... 
f=decorator(test)
f.__name__
'wrapper'
f
<function decorator.<locals>.wrapper at 0x0000020E56DB3280>

@decrator

初始化函数中,self后面的是实例化对象的属性,加下划线的意思代表这个属性是私有的,不应该被外部访问

class Person:
    def __init__(self, name, age):
        self._name = name
        self._age = age
    def get_name(self):
        return self._name
    def rename(self, new_name):
        self._name = new_name

p=Person('wang',14)
p.get_name()
'wang'
p.rename('li')
p.get_name()
'li'



class Person:
...     def __init__(self, name, age):
...         self._name = name
...         self._age = age
...     @property
...     def name(self):
...         return self._name
...     
p=Person('w',89)
p.name
'w'
p._name
'w'
p._age
89

继承

class Student(Person):
    pass # pass代表什么都不做只是占位而已

class Student(Person):
    #pass # pass代表什么都不做只是占位而已
    def set_score(self, score):
        self._score = score;
    def get_score(self):
        return self._score
s=Student('wang',11)
s.set_score(90)
s.get_score()
90

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由半码博客整理,本文链接:https://www.bmabk.com/index.php/post/140784.html

(0)

相关推荐

发表回复

登录后才能评论
半码博客——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!