定义函数
def f(x,y,z=4):
result = x + y + z
return result
#z的默认值为4
类(class)
class Person:
def _init_(self,name,height,weight):
self.name = name
self.height = height
self.weight = weight
def say_name(self):
print("我的名字叫"+self.name)
def say_hello(self,target_name):
print("很高兴见到你"+target_name)
person1 = Person("老张",170,100)
变量
1!=1.0
前者为整数,后者为小数
运算中有浮点数类型,结果也为浮点数
#整除运算符
a=7
b=3
a//3
int、float、complex、string
abs()取绝对值
round()四舍六入五留双
import
len()获取字符串长度
capitalize()字符串首字母大写
upper()所有字符均大写
lower()所有字符串均小写
replace()替换字符串的单词
string1 = "hello wolrd"
string1.replace("wolrd","world")
print(string1)
isupper()判断是否全部大写
更多函数可以参考python官方文档
split('o',2)#将字符串按o切割,切割两次
endwith()判断结尾字母
列表
list1=["字符串",["列表"],3,4,5]#列表嵌套列表,列表中类型可以不同
list1.append(6)
list1.pop(0)#默认为最后一项、参数为索引
print(len(list1))
list1.insert(索引,元素)
print(list1.index(索引))
list1.reverse()
list1.remove(3)
元组(不能修改的元组)
tupel1=(1,2,3)
list1=list(tupel1)#元组转换为列表
tupel2=tupel(list1)#列表转换为元组
字典
dict1={"name":"老张","height":170,"weight":100}
print(dict1["name"])
print(len(dict1))
dict1.keys()获得所有的键
dict1["name"]="老邓"
dict1["gender"]="男"
底朝天。pop("name")
集合
set1={1,2,3,4,,5}
set1=set((2,3,1,4,5))
print(set[0]) ×
set1.add()#加入元素
set1.discard(元素)#删除
set2 = {3,4,5,6}
set1.intersection(set2)#找到共有元素
set2.difference(set1)#找到集合2有而集合1没有的元素 输出为{6}
set3={1,2,3}
set2.issubset(set1)#判断是否为子集
str()#将数字、列表转换为字符串
新建一个列表就是新建了个地址
列表之间互相赋值是地址的互相赋值
if
...
elif
...
while():
...
for 命名变量名 in 遍历对象
range(开始(默认为0),结束(不包括),步长(默认为1))
break跳出循环;continue跳过后面部分执行下一个循环
python中用缩进代替C中的大括号
from ... import *导入全部
if _name_=="_main_":
print("我是主代码")#若在写这行代码的程序里面运行会进入这行
else:
print("我不是主代码")#若从外部导入(from ... import *)则进入这行