Python基础操作
基础学习
print()
输出函数
print('Hello Word!')
变量
变量名只能包含字母、数字、下划线,不能以数字开头,不能包含空格
bl = '我是大灰狼'
print(bl)
字符串
制表符\换行符
print('你好')
#制表符
print('\t你好')
#换行符
print('\n你好')
f字符串
f字符串,f是format(格式)的简写
first_name = 'sugar'
last_name = 'jerry'
# 通过把花括号内的变量转换为其值来设置字符串格式
full_name = f'{first_name} {last_name}'
print(full_name)
name = '猴子'
des = '大闹天宫'
zs = f'{name},{des}'
print(f'故事:{zs}!')
大小写转换
abc = 'sugar jerry BC'
# title以首字母大写的方式显示英文
print(abc.title())
# upper将字符串全部转换为大写
print(abc.upper())
# lower将字符串全部转换为小写
print(abc.lower())
删除空格
nn = ' qunidaye '
#删除末尾空格
print(nn.rstrip())
#删除开头空格
print(nn.lstrip())
#删除首尾空格
print(nn.strip())
数
整数
浮点数
所有带有小数点的数称为浮点数
数中下划线
money = 10_000_000_000
print(money)
常量
Python没有内置常量,可以用全字母大写来指出某个变量为常量
MAX_CONNECTIONS=500
数据类型转换
将不同的数据类型的数据拼接在一起
str()将其他数据类型转换为字符串
na = '孙悟空'
age = 19
print(type(na),type(age))
print('我叫'+na+",我今年"+str(age)+'岁')
int()将其他数据类型转换为整数
float()将其他数据类型转换为浮点
aq = '11'
pq = '23.66'
print(int(aq),float(pq))
注释
单行注释
以#开头,直到换行结束
多行注释
将一对三引号之间的代码称为多行注释
中文编码声明注释
在文件开头添加中文声明注释,用以制定编码格式
运算符
算术运算符
# 加
print(1+1)
# 减
print(6-2)
# 乘
print(5*5)
# 除
print(6/2)
# 整除
print(6//2)
# 余数
print(11%2)
#幂
print(2**3)
赋值运算符
# 链式赋值
a=1
b=a
print(b)
#参数赋值
c=8
c+=50
print(c)
#可在一行代码中给多个变量赋值
a,b,c = 1,2,3
比较运算符
e=8
h=11
print(e>h)
print(e>=h)
print(e!=h)
print(e<h)
q=100
p=100
#q与p的值相同
print(q==p)
#q与p的id相同
print(q is p)
布尔运算符
print(e==8 and h==11)
print(e==8 or h==11)
ui = 'wpordakel'
print('w' in ui)
位运算
位与&
位或|
左移位运算符<<
右移位运算符>>
input()
输入函数
ds = input("大圣你是什么职位?")
print(ds)
num1 = input('请输入第一个数:')
num2 = input('请输入第二个数:')
print('两数之和为:',num1+num2)
print('两数之和为:',int(num1)+int(num2))
列表
元素访问
列表是有序集合
索引从0开始
bl=['孙悟空','猪八戒','沙僧','唐三藏']
print(bl)
print(bl[0])
print(bl[-1])
print(f'西游记中师徒四人中大师兄是{bl[0]}')
元素修改
mot=['sugar','tom','join','jack']
mot[0]='jerry'
print(mot)
元素添加
# 在列表末尾添加元素
mot.append('mary')
print(mot)
# 在列表的任意位置添加元素
mot.insert(0,'duti')
print(mot)
元素删除
使用del可删除任意位置元素,条件是知道索引
# 删除元素
del mot[0]
print(mot)
使用pop()将元素从列表中删除,并接着使用它的值
#删除末尾元素
popmot=mot.pop()
print(mot)
print(popmot)
#删除指定位置元素
popmots=mot.pop(1)
print(popmots)
remove()根据值删除指定元素
#根据值删除元素
mot.remove('join')
print(mot)
#删除元素时,接着使用它的值
remot='jack'
mot.remove(remot)
print(mot)
注:remove()只删除第一个指定的值,如果要删除的值在列表中出现多次,需要使用循环来确保每个值都删除
排序
使用sort()可以对列表元素进行永久性的排序
cars=['fuid','oipl','ydte','aver','mqx','cnhs']
#正序
cars.sort()
print(cars)
# 倒序
cars.sort(reverse=True)
print(cars)
使用函数sorted()对列表进行临时排序
#保留列表元素原来的排列顺序
print(sorted(cars))
print(sorted(cars,reverse=True))
倒着打印列表
#按列表排列倒序打印
cars.reverse()
print(cars)
列表长度
carl=len(cars)
print(carl)
切片
blld=['car','cat','dog','home','apple','blue']
print(blld[1:3])
#默认从0开始
print(blld[:4])
#每隔2个元素提取一个值
print(blld[0:6:2])
#始于第一个元素,终于最后一个元素
print(blld[:])
数值列表
rg=range(1,10)
ran=list(range(1,10))
print(ran)
print(ran[0])
print(rg[2])
print(max(rg))
print(min(rg))
print(sum(rg))
元组
Python将不能修改的值称为不可变的,将不可变的列表称为元组
使用圆括号定义且元组中的值不能被修改
dem=(100,200,300)
print(dem[0])
字典
字典访问
#字典
dict_0={'color':'yellow','size':24}
print(dict_0['color'])
print(dict_0['size'])
# 有类似对象组成的字典
languages={
'jen':'python',
'sarah':'c',
'edward':'rudy',
'phil':'java',
'tom':'python'
}
language=languages['jen'].title()
print(language)
添加键值对
# 添加键值对
dict_0['height']=50
dict_0['site']='pagoda'
print(dict_0)
修改键值对
# 修改键值对
dict_0['color']='blue'
print(dict_0)
# 条件判断修改键值对
dict_1={'x':10,'y':20,'speed':'medium'}
print(f"old position:{dict_1['x']}")
if dict_1['speed']=='slow':
x_ince=1
elif dict_1['speed']=='medium':
x_ince=2
else:
x_ince=3
dict_1['x']=dict_1['x']+x_ince
print(f"new position:{dict_1['x']}")
删除键值对
# 删除键值对
dict_2={'color':'green','size':63}
print(dict_2)
del dict_2['size']
print(dict_2)
使用get()来访问值
dict_3={'color':'yellow','speed':'slow'}
# 没有对应的键值对-报错
# print(dict_3['size'])
# 使用方法get()在指定的键不存在时返回一个默认值
size_value=dict_3.get('size','没有相应的值')
print(size_value)
字典嵌套
dict_4={'color':'green','points':5}
dict_5={'color':'yellow','points':20}
dict_6={'color':'red','points':15}
dict_7=[dict_4,dict_5,dict_6]
for dict in dict_7:
print(dict)
aliens=[]
for alien_number in range(30):
new_alien={'color':'greed','points':5,'speed':'slow'}
aliens.append(new_alien)
for alien in aliens[:5]:
print(alien)
print('...')
print(f"Total number of aliens:{len(aliens)}")
字典中存储列表
pizza={
'crust':'thick',
'toppings':['mushrooms','extra cheese']
}
print(f"You ordered a {pizza['crust']}-crust pizza "
"with the following toppings:")
for topping in pizza['toppings']:
print("\t"+topping)
字典中存储字典
users={
'aeinstein':{
'first':'albert',
'last':'einstein',
'location':'princetion',
},
'mcurie':{
'first':'marie',
'last':'curie',
'location':'paris',
},
}
for username,user_info in users.items():
print(f"\nUsername:{username}")
full_name=f"{user_info['first']} {user_info['last']}"
location = user_info['location']
print(f"\tFull name:{full_name.title()}")
print(f"\tLocation:{location.title()}")
循环遍历
for循环
遍历整个列表
blld=['car','cat','dog','home','apple','blue']
for fbld in blld:
print(fbld)
print(f'my favorite is this:{fbld}')
print(fbld)
注:注意缩进问题
遍历数值列表
for re in range(1,6):
print(re)
squares=[]
for value in range(1,10):
square=re**2
squares.append(square)
print(squares)
列表解析
fosq=[rn**2 for rn in range(1,10)]
print(fosq)
遍历切片
blld=['car','cat','dog','home','apple','blue']
for pla in blld[:3]:
print(pla.title())
遍历字典
#遍历所有键值对
languages={
'jen':'python',
'sarah':'c',
'edward':'rudy',
'phil':'java',
'tom':'python'
}
for key,value in languages.items():
print(f'\bkey:{key}')
print(f'value:{value}')
# 遍历所有键
for name in languages.keys():
print(name.title())
# 遍历所有键
for vname in languages.values():
print(vname.title())
# 按特定顺序遍历所有键
for kname in sorted(languages.keys()):
print(kname.title())
whlie循环
num=1
while num<=10:
print(num)
num+=1
break
退出循环
prom='请输入您的年龄'
while True:
age=input(prom)
if int(age)<=18:
print("未成年不得进入")
break
else:
print("您已成年,请进入!")
continue
循环继续
number=0
while number<10:
number+=1
if number%2==0:
continue
print(number)
if语句
条件比较
# if循环
furn=['bed','cup','flower','kitchen','sofa']
for itun in furn:
if itun=='sofa':
print("成功")
elif itun == 'cuo':
print('成功')
else:
print("失败")
确定列表是否为空
#req=[]
req=['apple']
if req:
for reus in req:
print(f'Adding {reus}')
print('\n是否确定需要?')
else:
print('你需要什么?')
函数
定义函数
def sayhello():
"""显示简单的问候语"""
print("Hello!")
sayhello()
向函数传参
# 下方name为形参
def sayhello(name):
"""显示简单的问候语"""
print(f"Hello!My name is {name}!")
# 下方的参数'孙悟空'为实参
sayhello('孙悟空')
形参定义默认值
def sayhello(name='唐三藏'):
"""显示简单的问候语"""
print(f"Hello!My name is {name}!")
sayhello()
返回值
def get_name(first_name,last_name,middle_name=''):
"""返回整洁的姓名"""
full_name=f"{first_name} {middle_name} {last_name}"
return full_name.title()
gname=get_name('jie','tom')
print(gname)
传递列表
def greet_users(names):
for name in names:
print(f"Hello,{name.title()}")
unames=['cheng','guo']
greet_users(unames)
在函数中修改列表
def up_designs(designs,models):
while designs:
pop_designs=designs.pop()
print(f"开始打印模型:{pop_designs}")
models.append(pop_designs)
def show_models(models):
print("以下是所有打印好的模型:")
for model in models:
print(model)
designs=['phone','robor','room']
models=[]
up_designs(designs,models)
show_models(models)
传递任意数量的实参
def greet_users(*names):
for name in names:
print(f"Hello,{name.title()}")
greet_users('cheng','guo')
使用任意数量的关键字实参
可将函数编写成能够接受任意数量的键值对
在下面的示例中,函数build_profile()接受名和姓,还接受任意数量的关键字实参
def build_profile(first,last,**user):
user['firstname']=first
user['lastname']=last
return user
users=build_profile('cheng','guodong',age='21',sex='男')
print(users)
将函数存储在模块中
导入模块
创建名为pizza.py的模块文件
def make_pizza(size,*toppings):
"""简述要制作的披萨"""
print(f"\nMaking a {size}-pizza")
for topping in toppings:
print(f"- {topping}")
然后在项目中导入模块
import pizza
#如果模块中有多个函数,导入指定模块中的指定函数
#from pizza import make_pizza
pizza.make_pizza(16,'pepperoni')
pizza.make_pizza(12,'mush','peppers','cheese')
类
创建和使用类
#创建类
class Dog:
"""模拟小狗"""
def __init__(self,name,age):
"""初始化属性"""
self.name=name
self.age=age
def sit(self):
"""模拟小狗收到命令蹲下"""
print(f"{self.name} is now sitting.")
def roll_over(self):
"""模拟小狗收到命令时打滚"""
print(f"{self.name} rolled over!")
#调用方法
my_dog=Dog('Wellie',6)
your_dog=Dog('Lucy',3)
print(f"我的狗狗叫:{my_dog.name}")
print(f"我的狗今年{my_dog.age}岁了")
my_dog.sit()
print(f"你的狗狗叫:{your_dog.name}")
print(f"你的狗今年{your_dog.age}岁了")
your_dog.roll_over()
修改类属性的值
class Car:
"""模拟汽车"""
def __init__(self,make,model,year):
"""初始化汽车属性"""
self.make=make
self.model=model
self.year=year
# 给属性指定默认值
self.odometer=0
def get_des(self):
"""返回整洁的描述性信息"""
lomg_name=f"{self.year} {self.make} {self.model}"
return lomg_name.title()
def read_odometer(self):
"""打印一条指出汽车里程的消息"""
print(f"汽车里程为{self.odometer}英里")
# 将里程表读取设置为指定的值
def update_odometer(self,mileage):
self.odometer=mileage
# 将里程表读数增加指定的量
def inc_odometer(self,miles):
self.odometer+=miles
my_new_car=Car('audi','a4',2020)
print(my_new_car.get_des())
my_new_car.read_odometer()
# 修改属性的值
# 直接修改属性的值
my_new_car.odometer=23
my_new_car.read_odometer()
# 通过方法修改属性的值
my_new_car.update_odometer(40)
my_new_car.read_odometer()
#通过方法对属性的值进行递增
my_new_car.inc_odometer(100)
my_new_car.read_odometer()
继承
子类的方法
class Car:
"""模拟汽车"""
def __init__(self,make,model,year):
"""初始化汽车属性"""
self.make=make
self.model=model
self.year=year
# 给属性指定默认值
self.odometer=0
def get_des(self):
"""返回整洁的描述性信息"""
lomg_name=f"{self.year} {self.make} {self.model}"
return lomg_name.title()
def read_odometer(self):
"""打印一条指出汽车里程的消息"""
print(f"汽车里程为{self.odometer}英里")
# 将里程表读取设置为指定的值
def update_odometer(self,mileage):
self.odometer=mileage
# 将里程表读数增加指定的量
def inc_odometer(self,miles):
self.odometer+=miles
def remark(self):
print("发动机")
class ElectricCar(Car):
"""电动汽车的独特属性"""
def __init__(self,make,model,year):
"""初始化父类的属性"""
super().__init__(make,model,year)
#给子类定义属性和方法
"""再初始化电动汽车特有的属性"""
self.battery_size=75
# 给子类定义属性和方法
def des_battery(self):
"""打印一条描述电瓶容量"""
print(f"这辆车有{self.battery_size}-kwh 电量")
#重写父类方法
def remark(self):
print("电动车没有邮箱")
my_tesla=ElectricCar('tesla','model s',2020)
print(my_tesla.get_des())
my_tesla.des_battery()
my_tesla.remark()
将实例作用属性
class Car:
"""模拟汽车"""
def __init__(self,make,model,year):
"""初始化汽车属性"""
self.make=make
self.model=model
self.year=year
# 给属性指定默认值
self.odometer=0
def get_des(self):
"""返回整洁的描述性信息"""
lomg_name=f"{self.year} {self.make} {self.model}"
return lomg_name.title()
def read_odometer(self):
"""打印一条指出汽车里程的消息"""
print(f"汽车里程为{self.odometer}英里")
# 将里程表读取设置为指定的值
def update_odometer(self,mileage):
self.odometer=mileage
# 将里程表读数增加指定的量
def inc_odometer(self,miles):
self.odometer+=miles
def remark(self):
print("发动机")
#将实例用作属性
class Battery:
"""模拟电动车电瓶"""
def __init__(self,battery_size=75):
"""初始化电瓶的属性"""
self.battery_size=battery_size
def des_battery(self):
"""打印一条描述电瓶容量的消息"""
print(f"这辆车有{self.battery_size}-kwh 电量")
def get_range(self):
"""判断出电瓶的续航里程"""
if self.battery_size==75:
range=300
elif self.battery_size==100:
range=350
print(f"这辆车的续航里程是{range}")
class ElectricCar(Car):
"""电动汽车的独特属性"""
def __init__(self,make,model,year):
"""初始化父类的属性"""
super().__init__(make,model,year)
#给子类定义属性和方法
"""再初始化电动汽车特有的属性"""
self.battery=Battery()
my_tesla=ElectricCar('tesla','model s',2020)
print(my_tesla.get_des())
my_tesla.battery.des_battery()
my_tesla.battery.get_range()
导入类
car.py
class Car:
"""模拟汽车"""
def __init__(self,make,model,year):
"""初始化汽车属性"""
self.make=make
self.model=model
self.year=year
# 给属性指定默认值
self.odometer=0
def get_des(self):
"""返回整洁的描述性信息"""
lomg_name=f"{self.year} {self.make} {self.model}"
return lomg_name.title()
def read_odometer(self):
"""打印一条指出汽车里程的消息"""
print(f"汽车里程为{self.odometer}英里")
# 将里程表读取设置为指定的值
def update_odometer(self,mileage):
"""
将里程表读数设置为指定的值
拒绝将里程表往回调
"""
if mileage>=self.odometer:
self.odometer=mileage
else:
print("你不能将里程读数往回调")
# 将里程表读数增加指定的量
def inc_odometer(self,miles):
self.odometer+=miles
my_cat.py
from car import Car
my_new_car=Car('audi','a4',2020)
print(my_new_car.get_des())
my_new_car.odometer=10
my_new_car.read_odometer()
文件
从文件中读取数据
with open('E:\\PythonPeoject\\PyTeach\\resource\\pi_digits') as file_object:
contents=file_object.read()
print(contents)
逐行读取
with open('E:\\PythonPeoject\\PyTeach\\resource\\pi_digits') as file_object:
for line in file_object:
print(line)
读取文件创建列表
filename='E:\\PythonPeoject\\PyTeach\\resource\\pi_digits'
with open(filename) as file_object:
lines = file_object.readlines()
print(lines)
for line in lines:
print(line.rstrip())
写入文件
filename='E:\\PythonPeoject\\PyTeach\\resource\\progra'
with open(filename,'w') as file_object:
file_object.write("I LOVE YOU")
写入模式
读取模式(‘r’)、写入模式(‘w’)、附加模式(‘a’)、读写模式(‘r+’),如果省略了模式实参,默认只读模式打开
注:如果写入的文件不存在,函数open()将自动创建它
以写入模式打开文件,如果指定文件已存在,Python将在返回文件对象前清空该文件的内容
异常
异常处理try-excet代码块
try:
print(5/0)
# except:
#ZeroDivisionError异常:不能用数除以0
except ZeroDivisionError:
print("0不能作除数")
else代码块
try:
print('')
#ZeroDivisionError异常:不能用数除以0
except ZeroDivisionError:
print("0不能作除数")
else:
print("其他错误")
分析文本
filename='E:\\PythonPeoject\\PyTeach\\resource\\progra'
try:
with open(filename,encoding='utf-8') as f:
contents=f.read()
#FileNotFoundError异常:文件没有找到
except FileNotFoundError:
print("文件没有找到")
else:
#计算文件大致包含多少个单词
words=contents.strip()
#包含字符空格
num_words=len(words)
print(f"这个文件{filename}有大约{num_words}个单词")
存储数据
存储数据到json
import json
num=[1,2,4,6,11,13,18]
filename='E:\\PythonPeoject\\PyTeach\\resource\\num.json'
with open(filename,'w') as f:
json.dump(num,f)
将json中列表读取到内存
import json
filename='E:\\PythonPeoject\\PyTeach\\resource\\num.json'
with open(filename) as f:
numbers=json.load(f)
print(numbers)