Python学习笔记
数
- 任意两个数相除时,结果总是浮点数,即便这两个数都是整数且能整除
- 在其他任何运算中,如果一个操作数是整数,另一个操作数是浮点数,结果也总是浮点数
- 无论是哪种运算,只要有操作数是浮点数,Python默认得到的总是浮点数,即便结果原本是整数也是如此
数中的下划线
书写很大的数时,可以使用下划线将数字分组,打印时并不打印下划线,这种方法适用于整数和浮点数
age = 14_000_000_000
print(age)
同时给多个变量赋值
注意变量的个数和值的个数要相同
x,y,z = 0,1,2
print(x,y,z)
常量
将变量名全部大写来表示常量
AGE = 100
列表
name = ['a','b','c'];
print(name)
访问列表
name = ['a','b','c'];
print(name[0])
将列表元素首字母大写
name = ['a','b','c'];
print(name[0].title())
返回列表的最后一个元素
name = ['a','b','c'];
print(name[-1])
修改列表的元素
name = ['a','b','c'];
name[0] = e;
在列表中添加元素
在列表末尾添加元素
name = ['a','b','c'];
print(name)
name.append('e')
print(name)
在列表中插入元素
name = ['a','b','c'];
print(name)
name.insert(0,'e')
print(name)
从列表中删除元素
使用del删除元素
name = ['a','b','c'];
print(name)
del name[0]
print(name)
使用pop()删除元素
name = ['a','b','c'];
print(name)
name.pop();
print(name)
弹出列表中任意位置处的元素
name = ['a','b','c'];
print(name)
name.pop(1);
print(name)
根据值删除元素
remove只删除第一个指定的值,若列表中存在多个要被删除的值,则需要循环遍历删除
name = ['a','b','c'];
print(name)
name.remove('c');
print(name)
对列表排序
使用sort()对列表进行永久排序
name = ['b','a','d'];
print(name)
name.sort();
print(name)
使用sort()对列表进行反向永久排序
name = ['b','a','d'];
print(name)
name.sort(reverse = True);
print(name)
使用sorted()对列表进行临时排序
name = ['b','a','d'];
print(sorted(name))
print(name)
翻转列表的排列顺序
name = ['b','a','d'];
print(name)
name.reverse();
print(name)
确定列表的长度
name = ['b','a','d'];
print(len(name))
print(name)
遍历整个列表
names = ['a','b','c'];
for name in names:
print(name)
创建数值列表
使用函数range()
打印1~4
for val in range(1,5):
print(val)
使用range()创建数字列表
vals = list(range(1,6))
print(vals)
vals = list(range(0,6,2))
print(vals)
values = []
for value in range(1,11):
value = value**2
values.append(value)
print(values)
对数字列表进行简单的统计计算
digits = [1,2,3,4,5,6,7,8,9,0]
print(min(digits))
print(max(digits))
print(sum(digits))
列表解析
将for循环和创建新元素的代码合并成一行,并自动附加新元素
vals = [val**2 for val in range(1,11)]
print(vals)
使用列表的一部分
切片
name = ['a','b','c']
print(name[0:3])
遍历切片
names = ['a','b','c']
for name in names[:3]:
print(name)
复制列表
names = ['a','b','c']
names_1 = names[:]
print(names)
print(names_1)
元组
对比列表值不能修改
定义元组
names = ('a','b','c')
print(names[0])
print(names[1])
print(names[2])
遍历元组中的所有值
names = ('a','b','c')
for name in names:
print(name)
修改元组变量
names = (200,50)
print(names)
names = (400,100)
print(names)
if语句
检查是否相等
a = 'a'
b = 'a'
a==b
字典
字典是一系列键值对,每个键都与一个值相关联,可以使用键来访问相关联的值,与键相关联 的值可以是数,字符串,列表,甚至是字典,可以将python对象用作字典中的值
alien_0 = {'color':'green','points':5}
print(alien_0['color'])
print(alien_0['pionts'])
添加键值对
alien_0 = {'color':'green','points':5}
print(alien_0)
alien_0['x_position'] = 0;
alien_0['y_position'] = 25;
print(alien_0)
创建一个空字典
alien_0 = {}
alien_0['x_position'] = 0;
alien_0['y_position'] = 25;
print(alien_0)
修改字典中值
alien_0 = {'color':'green','points':5}
alien_0['color'] = 'yellow'
print(alien_0)
删除键值对
alien_0 = {'color':'green','points':5}
print(alien_0)
del alien_0['color']
print(alien_0)
由类似对象组成的字典
loves_languages = {
'jen':'python',
'tom':'c',
'tim':'tuby',
'jack':'C++'
}
print(loves_languages)
使用get()来访问值
loves_languages = {
'jen':'python',
'tom':'c',
'tim':'tuby',
'jack':'C++'
}
#存在输出第一个参数,不存在输出第二个参数
print(loves_languages.get('jen','yes'))
print(loves_languages.get('chen','no'))
遍历字典
user_0 = {'username':'tom',
'first':'jim',
'last':'jack'
}
for Key,Value in user_0.items():
print(f"\nKey:{Key}")
print(f"\nValue:{Value}")
遍历字典中的所有键
user_0 = {'username':'tom',
'first':'jim',
'last':'jack'
}
for Key in user_0.keys():
print(f"\nKey:{Key}")
按特定顺序遍历字典中的所有键
会先按键排序后输出
loves_languages = {
'jen':'python',
'tom':'c',
'tim':'tuby',
'jack':'C++'
}
for language in sorted(loves_languages.keys()):
print(language)
遍历字典中的所有值
loves_languages = {
'jen':'python',
'tom':'c',
'tim':'tuby',
'jack':'C++'
}
for language in loves_languages.values():
print(language)
对包含重复元素的列表调用set()
python会找出列表中独一无二的元素
loves_languages = {
'jen':'python',
'tom':'c',
'tim':'tuby',
'jack':'C++'
}
for language in set(loves_languages.values()):
print(language)
使用{}直接创建集合
花括号中没有键值对的时候,定义的可能是集合,不同于列表和字典,集合部队以特定的顺序存储元素
names = {'tom','jack','tim','tom'}
print(names)
字典列表
alien_0 = {'color':'green','points':'5'}
alien_1 = {'color':'yellow','points':'10'}
alien_2 = {'color':'red','points':'15'}
aliens = [alien_0,alien_1,alien_2]
在字典中存储列表
pizza = {'crust':'thick',
'toppings':['mushrooms','extra cheese']
}
print(pizza)
print(pizza['toppings'])
print(pizza['toppings'][0])
在字典中存储字典
users = {
'tom':{'id':0,'age':25,'sex':'man'},
'jack':{'id':1,'age':26,'sex':'man'}
}
print(users['tom'])
print(users['tom']['id'])
print(users['tom']['age'])
print(users['tom']['sex'])
用户输入和while循环
message = input('please input a int number:')
print(message)
使用int()来获得数值输入
使用函数input()时,Python将用户输入解读为字符串。
age = input('How old are you?')
age = int(age)
age>=18
while循环
i = 1;
while i<10:
print(i)
i = i + 1
使用break
flag = True
while flag:
message = input('please input a flag')
if message == 'quiz':
break;
else:
print('No')
在循环中使用continue
i = 0;
while i<10:
i = i + 1;
if i%2==0:
continue
print(i)
使用while循环处理列表和字典
unconfirmed_users = ['alice','tom','jack']
confirmed_users = []
while unconfirmed_users:
current_user = uncomfired_users.pop()
print(f"Verifying user: {current_user.title()}")
confirmed_users.append(current_user)
print('confirmed_users:')
for confirmed_user in confirmed_users:
print(confirmed_user.title())
删除特定值的所有列表元素
pets = ['dog','cat','rabbit','cat']
print(pets)
while 'cat' in pets:
pets.remove('cat')
print(pets)
使用户输入来填充字典
函数
定义函数
def greet_user():
"""显示简单的问候语"""
print('hello everyone')
greet_user()
向函数中传递信息
def greet_user(username):
"""显示简单的问候语"""
print(f"Hello,{username.title()}!")
greet_user('tom')
实参和形参数
关键字实参
def greet_user(username,username2):
"""显示简单的问候语"""
print(f"Hello,{username.title()},I am {username2}!")
greet_user(username2 = 'tom',username = 'jack')
默认值
def greet_user(username,username2 = 'tom' ):
"""显示简单的问候语"""
print(f"Hello,{username.title()},I am {username2}!")
greet_user(username = 'jack')
等效的函数调用
返回值
def sum(a,b):
return a+b
print(sum(2,2))
返回字典
def build_person(first_name,last_name):
"""返回一个字典,其中包含一个人的信息"""
person = {'first':'first_name','last':'last_name'}
return person
person = build_person('tom','jack')
print(person)
结合使用函数和while循环
传递列表
def greet_users(names):
"""向列表中每位用户发出简单的问题"""
for name in names:
msg = f"Hello,{name}"
print(msg)
usernames = ['tom','jack','tim']
greet_users(usernames)
在函数中修改列表
禁止函数修改列表
def greet_users(names[:]):
"""向列表中每位用户发出简单的问题"""
msg = f"Hello,{names.pop()}"
print(msg)
print(names)
usernames = ['tom','jack','tim']
greet_users(usernames)
print(usernames)
传递任意数量的实参数
*号代表创建一个名字为toppings的空元组,把接收到的所有值都封装到这个元组中
def make_pizza(*toppings):
print(toppings)
make_pizza('a')
make_pizza('a','b','c')
结合使用位置实参和任意数量实参
使用任意数量的关键字实参
def build_profile(first,last,**user_info):
"""创建一个字典,其中包含我们知道的关于用户的一切"""
user_info['first_name'] = first
user_info['last_name'] = last
return user_info
user_profile = build_profile('a','b',name = 'd',age = 'e')
print(user_profile)
将函数存储在模块中
def make_pizza(size,*toppings):
print(f"\nmakeing a {size}-inch pizza with the following toppings:")
for topping in toppings:
print(f"-{topping}")
import making_pizzas
making_pizzas.make_pizza(16,'baga')
making_pizzas.make_pizza(12,'naga','shi','laoba')
以模块名.函数名的方式调用
导入特定的函数
使用这种当时导入函数时,不需要用.因为import语句显式地导入了函数
from module_name import function_name
form module_name import function_0,function_1,function_2
使用as给函数指定别名
下面给函数make_pizza()指定了别名mp()。这是在import语句中使用make_pizza as mp实现的
from pizza import make_pizza as mp
mp(16,'a','b','c')
使用as给模块指定别名
import pizza as p
p.make_pizza(16,'a')
p.make_pizza(12,'a','b','c','d')
导入模块中的所有函数
from pizza import *
make_pizza(16,'a')
make_pizza(12,'a','b','c','d')
类
创建和使用类
创建Dog类
class Dog:
"""一次模拟小狗的简单尝试"""
def __init__(self,name,age):
"""初始化属性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} roll over")
mydog = Dog('tom',12)
print(mydog.name)
print(mydog.age)
mydog.sit()
mydog.roll_over()
mydog2 = Dog('jack',2)
print(mydog2.name)
print(mydog2.age)
mydog2.sit()
mydog2.roll_over()
方法__init__()
类中的函数被称为方法,init()是一个特殊的方法,每当创建Dog 类新实例时,Python都会自动运行它.在这个方法,
init两边都有两个下划线,每个与实例相关联的发放都自动传递实参self,它是一个指向自身的引用,让实例能够访问类中的属性和方法。
继承
子类继承了父类的所有属性和方法,同时还可以定义自己的属性和方法
在既有类的基础上编写新类,通常要调用父类的方法__init__(),
子类的方法__init__()
class Car:
def __init__(self,make,model,year):
self.make = make
self.model = model
self.year = year
self.odometer_reading = 0
def get_decriptive(self):
long_name = f"{self.year} {self.make} {self.model}"
return long_name.title()
def update_odometer(self,mileage):
if mileage >= self.odometer_reading:
self.odometer_reading = mileage
else:
print("you can't roll back odometer!")
def increment_odometer(self,miles):
self.odometer_reading += miles
class ElectricCar(Car):
def __init__(self,make,model,year):
super().__init__(make,model,year)
my_tesla = ElectricCar('tesla','model_s',2019)
print(my_tesla.get_decriptive())
super()是个特殊点的方法使我能够调用父类的方法,父类也称为超类
重写父类的方法
在子类中写一个与父类名字相同的方法,python将会不再考虑父类中的这个方法
将实例做属性
导入类
car.py
class Car:
def __init__(self,make,model,year):
self.make = make
self.model = model
self.year = year
self.odometer_reading = 0
def get_decriptive(self):
long_name = f"{self.year} {self.make} {self.model}"
return long_name.title()
def update_odometer(self,mileage):
if mileage >= self.odometer_reading:
self.odometer_reading = mileage
else:
print("you can't roll back odometer!")
def increment_odometer(self,miles):
self.odometer_reading += miles
class ElectricCar(Car):
def __init__(self,make,model,year):
super().__init__(make,model,year)
my_tesla = ElectricCar('tesla','model_s',2019)
print(my_tesla.get_decriptive())
from car import Car
从一个模块中导入多个类
from car import Car,ElectricCar
导入整个模块
import car
导入模块中的所有类
from module_name import *
导入整个模块比导入模块中的所有类好,避免了每个类可能引发的名称冲突
在一个模块中导入另一个模块
使用别名
from car import Car as My_Car
Python标准库
Python标准库是一组模块,我们可以使用标准库中的任何函数和类,在程序开头包含一句简单的import即可
文件和异常
读取整个文件
要以任何方式及使用文件,都要打开文件,才能访问它,函数open()接受一个参数:要打开的文件的文件名称。Python在当前执行的文件所在目录中查找指定的文件。open(‘test.txt’)返回一个表示文件test.txt的对象,Python将该对象赋值给file_object供以后使用,关键字with在不再需要访问文件后将其关闭。在这个程序中,调用了open(),但没有调用close()。也可以调用open()和close(),但是这样做可能存在bug导致方法close()未执行,文件将不会关闭,这样做可能导致数据丢失或者受损。有了标志test.txt的文件对象后,使用方法read()读取这个文件的全部内容,并将其作为字符串赋值给变量contents。相比原始文件,输出多了一行空行在最后,,因为read()到达文件末尾的时候返回一个空字符串,可以使用rstrip()删除空行
with open('test.txt') as file_object:
contents = file_object.read()
print(contents)
文件路径
每行的末尾都有一个看不见的换行符
file_path = '/Users/puheliang/PycharmProjects/pythonProject/demo1/test.txt'
with open(file_path) as file:
for line in file:
print(line)
创建一个包含文件各行内容的列表
使用关键字with时,open()返回的文件对象只在with代码块内可用。如果要在with代码块外访问文件的内容,可在with代码块内将文件的各行存储在一个列表中,并在with代码块外使用该列表:可以立即处理文件的各个部分,也可以推迟到程序后面再处理
filename = 'test.txt'
with open(filename) as file_object:
lines = file_object.readlines()
for line in lines:
print(line.rstrip())
使用文件的内容
filename = 'test.txt'
with open(filename) as file_object:
lines = file_object.readlines()
pi_string = ''
for line in lines:
pi_string += line.rstrip()
print(lines)
print(pi_string)
print(len(pi_string))
写入文件
写入模式(‘w’),附加模式(‘a’),读写模式(‘r+’),如果省略了模式实参,Python将以只读模式打开文件
在’w’模式下,如果指定的文件已经存在,Python将清空原来的文件的内容,Python只能将字符串写入文本文件,其他类型的数据需要用str()转换后储存
filename = 'test.txt'
with open(filename,'w') as file:
file.write('I love programming')
写入多行
filename = 'test.txt'
with open(filename,'w') as file:
file.write('I love programming\n')
file.write('nihao\n')
附加到文件
filename = 'test.txt'
with open(filename,'a') as file:
file.write('I am 蒲贺良\n')
file.write('I am 蒲牛逼\n')
异常
使用try-except代码块
try:
print(5/0)
except ZeroDivisionError:
print('No')
分析文本
title = 'I am 蒲贺良'
print(title.split())
存储数据
import json
numbers = [2,3,5,7,11,13]
filename = 'numbers.json'
with open(filename,'w') as f:
json.dump(numbers,f)
filename = 'numbers.json'
with open(filename) as f:
numbers = json.load(f)
print(numbers)
import pygame
class Ship:
"""管理飞船的类"""
def __init__(self,ai_game):
"""初始化飞船并设置其初始位置"""
self.screen = ai_game.screen
self.screen_rect = ai_game.screen.get_rect()
#加载飞船图像并获取其外接矩形
self.image = pygame.image.load('images/ship.bmp')
self.rect = self.image.get_rect()
#对于每艘新飞船,都将其放在屏幕底部的中央
self.rect.midbottom = self.screen_rect.midbottom
def blitme(self):
"""在指定位置绘制飞船"""
self.screen.blit(self.image,self.rect)