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注释
单行用#
"""多行
列表的而基本概念
向列表增加元素
从列表删除元素
排序
获取列表长度
遍历列表
需要循环的行的缩进和循环下面第一行相同即可
for ex in queue_name:
print(ex)
print(ex+"NB")
创建数值列表
for value in range(num1,num2)
print(value) #生成的数字"value"满足条件num1<=value
列表解析
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)
dimensions=(12,20,32)
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"])
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))
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?"))
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())#对实例的方法进行调用
from car import Car
from car import Car,Electric_car
from car import *
filename = 'pi_digits.txt'
with open(filename) as file_object:#打开了一个文件,并用"file_object"来接收这个文件
lines = file_object.readlines()#将文件的每一行都输出出来
for line in lines:
print(line.rstrip())#删除空白符
常用函数
注意事项
file_name="test.txt"
with open(file_name,"w") as file_object:#类比C语言
file_object.write("I love python!")
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 | 类型错误(通常输出数值类型为字符串的时候没有转换) |
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)
import json
filename="test.json"
with open(filename) as f1_obj:
ss=json.load(f1_obj)
名字 | 功能 |
---|---|
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
转载请注明出处