目录
python的优点:
解释型、面向对象的高级编程语言
python的特性:
开源、易于维护、可移植
易于使用、简单优雅
广泛的标准库、功能强大(集成了很多标准库)
可扩展、可嵌入
python的应用:
数据分析、科学计算、常规开发、WEB开发、人工智能
python环境安装:
选择与自己电脑匹配版本下载
配置环境变量
//Dos窗口输入
python
python数据类型:
数字(number)
Python Number数据类型用于存储数值,包括整型、长整型、浮点型、复数
Python中数学运算常用的函数基本都在math模块
import math
print(math.ceil(4.1)) #返回数字的上入整数 5
print(math.floor(4.9)) #返回数字的下舍整数 4
print(math.fabs(-10)) #返回数字的绝对值 10.0
print(math.sqrt(9)) #返回数字的平方根 3.0
print(math.exp(1)) #返回e的x次幂 2.718281828459045
Python中随机数
随机生成一个[0,1)范围内的实数
import random
ran=random.random()
print(ran)
#0.514062566089323
随机生成一个[1,20)范围内的整数
ran=random.randint(1,20)
print(ran)
#13
当使用random.seed(x)设定好种子之后,random()生成的随机数将会是同一个
random.seed(10)
print("Random number with seed 10:",random.random)
#Random number with seed 10: 0.5714025946899135
字符串(String)
Python中的字符串可以使用单引号、双引号和三引号(三个单引号或者三个双引号 )括起来,其中可以使用反斜杠\转义特殊字符
print('Hello World')
print("Hello World")
print('''Hello World''')
str="Hello World"
Str1='''Hello World'''
print(str)
print(str1)
字符串的连接
1.使用+运算符
str1="Hello"
str2="World"
print(str1+str2)
2.使用join运算符
str='-'.join('Hello')
print(str)
#H-e-l-l-o
列表(List)
声明一个列表,并使用下标访问元素
#声明一个列表
names=['jk','tm','tn','sm','j']
#通过下标或索引获取元素
print(names[0])
#获取最后一个元素
print(names[-1])
print(names[len(names)-1])
#获取第一个元素
print(names[-5])
列表查询
查询names列表中有没有值为‘sm’的元素
#声明一个列表
names=['jk','tm','tn','sm','j']
#查询names中有没有“sm”
#遍历
flag=0
for name in names :
if name == 'sm':
print('存在')
flag=1
break
if flag==0:
print('不存在')
#使用in关键字
if 'sm' in names:
print('存在')
else:
print('不存在')
列表添加
#append():末尾追加
girls.append('y')
print(girls)
#extend():合并列表
models=['l','x']
girls.extend(models)
#girls=girls+models
print(girls)
#insert():在指定位置添加
girls.insert(1,'s')
print(girls)
列表修改
#修改指定元素
fruits=['apple','pear','香蕉','pineapple','草莓']
print(fruits)
fruits[-1]='strawberry'
print(fruits)
#将fruits列表中的‘香蕉’替换为'banana'
for i in range(len(fruits)):
if '香蕉' in fruits[i]:
fruits[i]='banana'
break
print(fruits)
错误案例
for fruit in fruits:
if '香蕉' in fruits:
fruit='banana'
print(fruits)
列表删除
#列表删除
words=['cat','hello','pen','pencil','ruler']
del words[1]
print(words)
words.remove('pencil')
print(words)
words.pop(1)
print(words)
列表切片
[]中设置要使用的第一个元素和最后一个元素的索引,左闭右开
元素 | cat | dog | tiger | snake | mouse | bird | bear |
正向 | 0 | 1 | 2 | 3 | 4 | 5 | 6 |
负向 | -7 | -6 | -5 | -4 | -3 | -2 | -1 |
#列表删除
animals=['cat','dog','tiger','snake','mouse','bird','bear']
print(animals[2:5])
#['tiger', 'snake', 'mouse']
print(animals[-1:])
#['bear']
print(animals[-3:-1])
#['mouse', 'bird']
print(animals[::2])
#['cat', 'tiger', 'mouse', 'bear']
print(animals[-5:-1:2])
#['tiger', 'mouse']
列表排序
#生成10个不同的随机数,存至列表中,并进行排序
random_list=[]
i=0
while i<10:
ran=random.randint(1,20)
if ran not in random_list:
random_list.append(ran)
i+=1
print(random_list)
#[15, 11, 8, 9, 2, 4, 7, 10, 18, 16]
#默认升序
new_list=sorted(random_list)
print(new_list)
#[1, 3, 7, 8, 10, 11, 14, 15, 18, 19]
#默认降序
new_list=sorted(random_list,reverse=True)
print(new_list)
#[19, 18, 15, 14, 11, 10, 8, 7, 3, 1]
元组(Tuple)
与列表类似,区别是元组中的内容不可修改
注:元组中只有一个元素时,需要在后面加逗号
tuple1=()
print(type(tuple1))
#<class 'tuple'>
tuple2=('hello')
print(type(tuple2))
#<class 'str'>
tuple3=('hello',)
print(type(tuple3))
#<class 'tuple'>
问:元组不能修改,所以不存在往元组中加入元素,作为容器的元组,如何存放元素?
#列表转化为元组
random_list=[]
for i in range(10):
ran=random.randint(1,20)
random_list.append(ran)
print(random_list)
#[5, 20, 19, 5, 8, 19, 18, 14, 11, 6]
random_tuple=tuple(random_list)
print(random_tuple)
#(5, 20, 19, 5, 8, 19, 18, 14, 11, 6)
元组切片以及一些函数
random_list=[]
for i in range(10):
ran=random.randint(1,20)
random_list.append(ran)
print(random_list)
#[5, 20, 19, 5, 8, 19, 18, 14, 11, 6]
random_tuple=tuple(random_list)
print(random_tuple)
#(5, 20, 19, 5, 8, 19, 18, 14, 11, 6)
print(random_tuple[0])
#4
print(random_tuple[-1])
#6
print(random_tuple[1:3])
#(3, 3)
print(random_tuple[::-1])
#(6, 11, 8, 20, 1, 6, 8, 3, 3, 4)
print(max(random_tuple))
#20
print(min(random_tuple))
#1
print(sum(random_tuple))
#70
print(len(random_tuple))
#10
元组的拆包与装包
#元组元素个数与变量个数相等:
#定义一个元组
t1=(1,2,3)
#将元组赋值给变量a,b,c
a,b,c=t1
print(a,b,c)
#1 2 3
#元组元素个数与变量个数不相等:
#定义一个元组
t2=(1,2,3,4,5)
#1 2 [3, 4, 5]
#将t2[0],t2[1]分别赋值给a,b;其余的元素装包后赋值给c
a,b,*c=t2
print(a,b,c)
字典(Dict)
#定义一个空字典
dict1={}
#定义一个字典的同时,进行初始化
dict2={'name':'y','weight':45,'age':25}
print(dict2['name'])
#y
#添加元素
dict1['name']='y'
dict1['weight']=43
print(dict1)
#{'name': 'y', 'weight': 43}
#修改字典元素
dict1['weight']=44
print(dict1)
#{'name': 'y', 'weight': 44}
字典相关函数
items()取出键值对
keys()取出键
values()取出值
dict={'yang':165,'yu':166,'shang':164}
print(dict.items())
#dict_items([('yang', 165), ('yu', 166), ('shang', 164)])
for key,value in dict.items():
if value > 165:
print(key)
#yu
names=dict.keys()
print(names)
#dict_keys(['yang', 'yu', 'shang'])
hights=dict.values()
print(hights)
#dict_values([165, 166, 164])
total=sum(hights)
avg=total/len(hights)
print(avg)
#165.0
类(Class)
1、_init()_定义构造函数,与其他面向对象语言不同的是,Python语言中,会明确地把代表自身实例的self作为第一个参数传入
2、创建一个实例化对象cat,init()方法接收参数
3、使用点号.来访问对象的属性
class Anmial:
def __init__(self,name):
self.name=name
print('名称实例化')
def eat(self):
print(self.name+' needs eat sth')
# 按间距中的绿色按钮以运行脚本。
if __name__ == '__main__':
cat=Anmial('miao')
print(cat.name)
#名称实例化
#miao
cat.eat()
#miao needs eat sth
继承
通过继承创建的新类称为子类或派生类,被继承的类称为基类、父类或超类
class Anmial:
def __init__(self,name):
self.name=name
print('名称实例化')
def eat(self):
print(self.name+' needs eat sth')
class Cat(Anmial):
def __init__(self,name):
self.name=name
print('猫的名称实例化')
def eat(self):
print(self.name+' needs eat fish')
# 按间距中的绿色按钮以运行脚本。
if __name__ == '__main__':
cat=Anmial('miao')
print(cat.name)
#名称实例化
#miao
cat.eat()
#miao needs eat sth
#实例化子类
cat1 = Cat('miao1')
print(cat1.name)
# 猫的名称实例化
# miao1
#调用子类方法
cat1.eat()
# miao1 needs eat fish
#调用父类方法
cat1.eat1()
#miao1 needs eat fish1
JSON
JSON序列化和反序列化
JSON序列化
json.dumps用于将python对象编码成JSON字符串
data=[{'a':1,'d':4,'b':2,'c':3}]
#json=json.dumps(data)
#print(json)
json_format=json.dumps(data,sort_keys=True,indent=4,separators=(',',':'))
#使用indent=4 这个参数优化输出格式
print(json_format)
[
{
"a":1,
"b":2,
"c":3,
"d":4
}
]
JSON反序列化
json.loads用于解码JSON数据。该函数返回python字段的数据类型
jsonData='{"a":1,"b":2,"c":3,"d":4}'
text=json.loads(jsonData)
print(text)
#{'a': 1, 'b': 2, 'c': 3, 'd': 4}
Python异常处理
try/except语句用来检测try语句块中的错误,从而让except语句捕获异常信息并处理
finally中的内容,退出try时总会执行
try:
fh=open("D:/test1.txt","w")
fh.write("这是一个测试文件")
except IOError:
print('Error:没有找到文件或读取文件失败')
else:
print('写入成功')
finally:
print('关闭文件')
fh.close()