蛇皮书
字符串
Python 区分大小写
大小写转换
String_Name.title() #所有单词首字母大写
String_Name.upper() #所有单词所有字母大写
String_Name.lower() #所有单词所有字母小写
空白符处理
String_Name.strip() #删除空白符
String_Name.lstrip() #删除字符串首空白符
String_Name.rstrip() #删除字符串尾空白符
数字与字符转换
str(xxx) #将xxx转化为字符串
int("152") #将"152"转化为数字152
数学运算
次方数
2**8 2的8次方
对列表操作的最大值,最小值函数
最小 | 最大 | 求和操作 |
---|---|---|
min(queue_name) | max(queue_name) | sum(queue_name) |
注释
Python注释
单行用#
"""多行
列表
-
列表的而基本概念
- 列表约等于数组,ex byci=[‘a’,‘b’],访问原则和数组相似
- 列表[-1]代表最后一个元素
-
向列表增加元素
- queue_name.append(element) 可以加一个元素到列表末尾
- queue_name.insert(num,element) 可以加一个元素到列表指定位置,其后的元素向后移动一个单位
-
从列表删除元素
- del queue_name[num] 删除指定位置的元素
- queue_name.pop() 删除列表末尾最后一个元素,并返回该元素的值
- queue_name.pop(num) 删除列表指定位置的某个元素,并返回该元素的值
- remove(element) 根据元素的值删除遇到的第一个等于该值的元素,并返回该元素的值
-
排序
- queue_name.sort() 对列表元素进行排序,不可恢复原状
- queue_name.sort(reverse=True/False) 对列表元素进行正/反排序
- sorted(queue_name) 对列表元素进行临时排序
- queue_name.reverse() 将元素按照和原来的列表相反的顺序进行排列
-
获取列表长度
- len(queue_name) 返回一个表示元素个数的数字
-
遍历列表
需要循环的行的缩进和循环下面第一行相同即可
for ex in queue_name: print(ex) print(ex+"NB")
-
创建数值列表
for value in range(num1,num2) print(value) #生成的数字"value"满足条件num1<=value<num2
- queue_name=list(range(num1,num2)) 将生成的数字之间转化为列表
-
列表解析
number_queue=[value**2 for value in range(1,3)] #生成1到2所有数字的平方的队列
-
禁止直接使用列表
如果列表重要,那么不要直接使用,应该创建副本
function_name(list_name[:])
-
切片
people=["dav","aseic","monia","nia"] student=(people[1:3]) #将people的第一二个元素赋值给student student=(people[1:]) #将people第二个开始的所有元素赋值给student student=(people[:2]) #将people前三个元素赋值给student student=(people[:]) #将people的所有元素赋值给student
- 遍历切片
for a in quene[0:3]: print(a)
元组tuple
- 元组创建
dimensions=(12,20,32)
- 元组的特点
- 不能改变其中的值
- 可以用for循环遍历元组的所有元素
- 可以重新定义整个元组达到修改的目的
if语句
if age>1:
print("age>1")
elif age<1:
print("age<1")
else:
print("age=1")
-
and 或者 or 可以对条件并列
-
检测特定值是否被包括
if "a" in title_queue: print("yes") if "b" not in title_queue: #not in 语法 print("no")
-
Python可以使用布尔值=》True/False
-
Python可以用else if类型,else可以省略
字典
student_info={"name":"David","age":15}
#访问字典中的值
print(student_info["name"]+"'s age is "+str(student_info["age"]))
#增加键
student_info["home"]="chengdu"
student_info["family_member"]=3
#删除键
del student_info["age"]
#修改值
student_info["family_member"]=4
student_info["family_member"]=student_info["family_member"]+1
#创建空字典
teacher_info={}
- 遍历字典
#遍历键和键值 for k,v in student_info.items(): print(k+v) #遍历键 for k in student_info.keys(): print("The key is\t"+k) #遍历键值 for v in student_info.values(): print("The value is\t"+str(v)) #顺序遍历 for key_name in sorted(student_info.keys()): print(key_name)
嵌套
- 字典列表
student_info=[] for student in range(1,31,1): student={"name":"David","age":16,"hobbies":["swimming","jogging"]} student_info.append(student)
- 字典中储存列表
student={"name":"David","age":16,"hobbies":["swimming","jogging"],} for hobby in student["hobbies"]: print(hobby)
- 字典中储存字典
parents={"mom":{"name":"queen","age":70,},"Father":{"name":"lord","age":80,},} print(parents["mom"]["name"])
input 用户输入
message=input("Please input something")
print("What you input is\t"+message)
#可以用变量储存语句
HelpWords="Please input something"
OutPutWords="What you input is\t"
message=input(HelpWords)
print(OutPutWords+message)
#int()得到数值
num=int(input("Please input your age:\t"))
print("One year later you will be "+str(num+1))
while 循环
i=0
while True
print("This is True!")
i+=1
if(i>5)
break
在列表移动元素
unconfirmed_student=["A","B","C"]
confirmed_student=[]
while unconfirmed_student:
current_student=unconfirmed_student.pop()
confirmed_student.append(current_student)
print(confirmed_student)
#删除包含特定的值的所有列表元素
while "B" in unconfirmed_student:
unconfirmed_student.remove("B")
#根据输入生成字典
response=[]
input_choice=True
while input_choice:
input_name=input("What is your name?\n")
input_address=input("Where do you live in?\n")
input_age=input("How old are you?\n")
response.append({"name":input_name,"address":input_address,"age":input_age})
if(input("Exit? \nChoose'Y/N'").upper()=="Y"):
break
for student in response:
print(student)
函数
def helloWorld():
print("Hello Py World!")
return True
- 关键字实参
def describe_pet(animal_type,animal_name): return "My "+animal_type+"'s name is "+animal_name
- 等效的调用
describe_pet("dog","Harry") describe_pet(animal_type="dog",animal_name="Harry") describe_pet(animal_name="Harry",animal_type="dog")
- 默认值
注意,等号两边不能有括号 def describe_pet(animal_type,animal_name="Bob"): return "My "+animal_type+"'s name is "+animal_name 等效的调用 describe_pet("cat") #代表顺序传入参数,此时就是"animal_type" describe_pet("cat","Bob") describe_pet(animal_type="cat")
- 返回值
- 返回字典
def perSon_detail(first_name,last_name): perSon_name={"firstName"=first_name,"lastName"=last_name} return perSon_name
- 返回字典
- 传递任意数量的实参
def print_students(*student): print(student) print_students("Lina","David") #会将实参转化为一个元组进行使用
- 结合使用位置实参和任意数量实参(元组)
def print_students(num,*student): """这个时候num当做正常参数使用""" print_students(2,"Lina","David")
- 使用任意数量的关键字实参(字典)
def print_students(**student): for k,v in student.items(): print(k+"'s birthday is on "+v) print_students(name=input("name?"),birthday=input("birthday?"))
模块
函数储存在模块内
- 导入整个模块
import test_suite test_suite.print_students(name=input("name?"),birthday=input("birthday?")) """就可以对test_suite里面的东西直接进行使用"""
- 导入特定的函数
import test_suite print_students,other_funtion_name#导入模块内指定函数 print_students(name=input("name?"),birthday=input("birthday?"))
- 使用as创建别名
import test_suite as ts ts.print_students(name=input("name?"),birthday=input("birthday?"))
- 使用模板里面的所有函数
from test_suite import * test_suite.print_students(name=input("name?"),birthday=input("birthday?"))
类
class Student():
def _ini_(self,name,age):
self.name=name
self.age=age
def sleep(self):
print(self.name.title()+"is sleeping")
- 类的初始化方法:
_init_()
- 实例
student_1=Student("Bob",14)
- 调用方法
student_1.sleep()
- 继承
class Father(): def __init__(self,name,age):#这里是一侧两个下划线,注意!! self.name="me" def birth_baby(self): print("new baby gets born!") class Son(Father):#表示继承Father def __init__(self,name,age): #super().__init__(name,age) super(Son,self).__init__(name,age)#调用父类构造器,初始化,pyhton2.7的用法 self.age=age def print_detail(self): print(""+self.name+self.age) #对父类的方法进行重写 def birth_baby(self): print("He is just a Son!") a=Son("Bob","46") a.print_detail() a.birth_baby()
- 将其他类用作一个类的属性
class Car(): def __init__(self,size): self.battery=Battery(size)#将battery的实例作为Car的一个属性 class Battery(): def __init__(self,size): self.size=size def describe_battery(self): print("this is a "+self.size+" battery!") a=Car("85") print(a.battery.describe_battery())#对实例的方法进行调用
- 导入类
- 从"car.py"这个模块里面导入"Car"这个类
from car import Car
- 从"car.py"这个模块里面导入"Car,Electric_car"这两个类
from car import Car,Electric_car
- 从"car.py"这个模块里面导入所含的所有类
from car import *
- 从"car.py"这个模块里面导入"Car"这个类
文件处理
读取文件
filename = 'pi_digits.txt'
with open(filename) as file_object:#打开了一个文件,并用"file_object"来接收这个文件
lines = file_object.readlines()#将文件的每一行都输出出来
for line in lines:
print(line.rstrip())#删除空白符
-
常用函数
- rstrip()
- 默认情况删除最后的空格
- rstrip(“k”)删除"k"
- readlines()
- 读取文件下一行
- open()
- 到指定文件目录下面打开文件
- windows系统下使用""
- linux系统使用"/"
- with关键字
- 能让python妥善的打开和关闭文件
- read()
- 读取整个文件,并储存在内存中
- replace()
- String_name.replace(“A”,“B”) 将字符串中的"A"全部替换为"B"
- split()
- 对一个句子进行分解,默认是将按照空格分解句子,括号内可以放参数(按照对应参数的字符分割)
- rstrip()
-
注意事项
- 不要使用close(),python会自动关闭,否则一旦还有使用,会报错
写文件
- 写空文件
file_name="test.txt" with open(file_name,"w") as file_object:#类比C语言 file_object.write("I love python!")
- 常用函数
- write()
- 写入文件,按行写入
- 不会自动换行,需要"\n"
- open()
- “w” 删除整个文件重写
- “a” 文件末尾附加
- write()
异常
-
try-expect代码块
检测try里面代码是否会出错,如果出错,下面的except的后面就是可能存在的错误
try: answer=print(5/0) except ZeroDivisionError:#如果存在"ZeroDivisionError"这个错误,那么执行下面的语句 print("0 can't be devided!") else: print(answer)
-
else
对于"try"里面内容进行正常运行的情况,执行else
-
pass
对于这个except Error的内容什么也不做 -
常见的错误类型
类型 | 说明 |
---|---|
ZeroDivisionError | 除数为零 |
FileNotFoundError | 找不到文件 |
ValueError | 类型错误(通常输出数值类型为字符串的时候没有转换) |
存储数据
- 存储信息用"json"格式进行
- 写入json
import json answer=[1,2,5,9,96,3,5,7,4,7,5,987,5] print(answer) filename="test.json" with open(filename,"w") as f_obj: json.dump(answer,f_obj)
- 读json
import json filename="test.json" with open(filename) as f1_obj: ss=json.load(f1_obj)
- 常用函数
- 写入json
名字 | 功能 |
---|---|
json.dump() | 写入 |
json.load() | 装载 |
错误信息
序号 | 错误 | 原因 |
---|---|---|
1 | unindent does not match any outer indentation level | 代码缩进不一致 |
2 | TypeError:takes no arguments | 初始化构造器"init"出现问题,下划线少了或者不够 |
3 | IndentationError: unindent does not match any outer indentation level | 代码Tab对齐问题,和空格混用了 |
匿名函数
bar=lambda x+y
# 调用
# x=10
# y=2
# bar()
#>>>12
转载请注明出处