Python基础知识
·
```python
#单行注释
'''一对三引号或者一对6引号就是注释,或者自动识别'''
#coding=gbk
#四个空格=一个缩进量=1TAB键,不然会出现SyntaxError异常
#模块名小写+_ 包名类似 类名每个单词首字母大写:BorrowBook
#__开头表示是私有的
#注意保留字是区分大小写的
#标识符:字母、数字、下划线且第一个字符不能是数字
#汉字可以作为标识符但不推荐
#__me__()表示构造函数 __add 表示私有成员 _width 表示不能直接访问的类属性,也不能通过from或者import导入
#不需要定义变量,直接使用
#动态类型语言,变量类型可以随时变化,注意使用半角,全角是为中文提供的
#整数的位数任意 0o/0O 八进制 0x/0X 十六进制
# \ 续航符 \0 空 \" \\ \f 换页 \0dd八进制 \xhh十六进制
import keyword
keyword.kwlist #及为查看关键字
print("i am good\
可以接上去")
print("i am good"
"也可以接上去")
no=1024
number=1024
id(no)
id(number)#二者是一样的
type(no) #查看类型
number=str(1024) #数值转换为字符串
number=3.14+2.5j #j表示的是虚部
a="12234"
b='1234'
c='''1223
3'''#只有这种可以变成多行形式,且该类型引号作为字符串的定界符,保留原本格式不需要转义
print(r"我的python\02") #有r就是按照原样输出
#False+1=True的boolean可以进行转化
#False None 0 0.0 0j 空的序列,字符串,列表。元组为假,其余都为真
float(a)
complex(2,3)#创建复数
repr(x) #表达式字符串
eval(str)#计算字符串的有效表达式,并且返回一个对象
chr(10) #将整数变为一个字符
ord(x) #变为字符对应的整数值
hex(16) oct(8) bin()
money_real=int(money_all)
money_key=str(money_real)
age=int(input("这是提示信息,并不受影响"))#input 返回的是字符串数据
print(a*b) #只有是字符串输出的时候才需要双引号
print(a,b) #同行输出
fp=open(R'D:\mot.txt','a+')
print("我的python",file=fp)
fp.close()
# //取整除,返回商的整数部分 2**3 7/2=3.5 并非3
# %在除数是负数时,结果也是负数 //= **=
#逻辑运算符:and or not
#& | ^ 按位计算
print("12&8="+str(12&8))
#移位计算速度很快,当要使用2**n时就可以
#算数计算>位运算>比较运算
#python 没有switch计算,没有do while
if a>b:max=a
b=a if a>0 else -a
if flag:
elif not flag:
elif :
# 不能对布尔类型进行比较 flag==True
while none:
number+=1
if number%3==2 and number%5 ==3 and number%7 ==2:
print("大约这个数",number)
none=False
for i in range(101):
range(start,end,step)
print(i,end=' ') #表示在这里用一行表示出
string="不要再说不可能"
for ch in string:
print(ch)
#打印9*9乘法表
for i in range(1,10)
for j in range(1,i+1)
print(str(j)+"x"+str(i)+"="+str(i*j)+"\t",end='')
if a>b:
break
if a<b:
continue
else:
pass #只是起到占位作用
print("")
# 序列,列表
#序列是一块用于存储多个值的连续储存空间
#Index 从右到左-1~-n 从左到右 0~n 后者减前者=n
verse=['12','23','23','34']
print(verse[2])
#切片访问一定范围的元素,生成一个新的序列
sname[strat:end:step]
sname[:]#就是表示复制整个序列
#列表可以相加,直接加到后面
#相同序列相加,是指的是同为列表,元组,字符串,类型可以不同
print(verse*3) #表示重复n次的效果
emptylist=[None]*5
print("晴空一盒" not in verse) #判断是否在里面
#len() max() min() 都可以在序列中使用,返回最大元素或者返回最小元素
#list() str() sum() sorted() reversed() enumerated()
#转换为列表 转换为字符串 计算元素和 对元素进行排序 反转 将序列变成一个索引序列,多用在for中???
listname=[el,er,et,ed] #不同类型的数据放进去,但一般不这样
for item in verse:
print(item) #遍历输出元素的值
listname=[] #创建空列表
list(data) #里面可以是range对象,字符串,元组,或者其他可以迭代的数据
list(range(10,20,2))
del listname #一般不用,python会自动识别
#如果还没有出现过则显示name verse is not defined
datetime.datetime.now()#是用来获取当前日期,而weekday()是获得日期0为一~6天
for index,item in enumerate(verse):
print(index,item)
#输出诗句
if index%2==0:
print(item+",",end=' ')
else :
print(item+"。")
listname.append(obj) #为列表添加元素
numberlist=[]
a=6
while True:
if a%2==0:
a=a//2 #这样整除才能得到整数
else:
a=a*3+1
numberlist.append(a)
if a==1:
break
print("这个列表是",numberlist)
# insert 在指定位置插入元素
verse2.extend(verse1) #将verse1的元素全部追加到verse2中
# 修改列表中的元素只需要通过索引获取,然后重新赋值即可,删除指定元素也可以使用del+索引获取
verse.remove("过大百年") #如果指定的元素不存在,那么会抛出ValueError异常,所以最好先判断是否存在
if verse.count(value)>0: # count是判断出现的次数,返回0就说明没有出现过
verse.remove(value)
listname.index(obj) # 显示首次出现时的下标,不然会弹出ValueError:"贵"is not in list
sum(iterable[,list]) # 后面是计算之后后要加一个数值时才会使用
listname.sort(key=None,reverse=False) # False是升序(默认),True是降序,设置key=str.lower就表示排序不区分大小写,sort是先对大写字母排序,再对小写字母排序
# sort不能直接对中文排序,需要重新编写
sorted(iterable,key=None,reverse=False) # 内置函数,区别于列表对象的方法,排序后原列表的元素顺序不变
grade_des=sorted(grade,reverse=True) # 进行降序排列,会建立一个原列表的副本
randomnumber=[random.randint(10,100)for i in range(10)]
list=[Expression for var in range] # 列表推导式,快速生成列表
newlist=[Expression for var in list] # 根据指定列表生成列表 pop()
price=[1200,123,123,123]
sale=[int(x*0.5) for x in price] # 这个x就相当于那个遍历对象
salw=[x for x in price if x>500] # if condition 满足条件的就可以被生成
listname=[[1,2,3,4],
[1,2,3,4],
[1,2,3,4]] # 这样排版好看,二维列表
arr=[]
for i in range(4):
arr.append([])
for j in range(5):
arr[i].append(i) # 通过遍历创建二维列表
arr=[[j for j in range[5]]for i in range(4)] # 通过列表推导式创建
# 竖版输出
verse.reverse
for i in range(5): # 原本是4~5的组成,list也可以将字符串转化为列表
for j in range(4):
if(j==3):
print(verse[j][i])//相当于矩阵的翻转
else:
print(verse[j][i],end=" ")
# 元组
# 元组为不可变序列,类型也可以不同,用来保存程序中不可修改的内容
tuplename=(1,2,3,4)
tuplename2=1,2,3,4 # python也自动将他看做元组,输出元组时也有()在外面
verse=("12",) # 这个是输出单个元组,type=tuple
verse=("12") # 这个是输出字符串,type=str
verse2=() # 空元组
tuple1=tuple(range(10,20,2)) # 这个函数里面是可以转换为tuple的data
del tuple1 # 不建议,理由同上
print(untitel[0]) # 在输出单个元组元素时没有小括号,字符串时还没有左右引号
print(untitel[:3]) # 切片方式输出前3个put()
# enumerate()函数用于将一个可遍历的数据对象组合成一个索引序列,同时输出数据和数据下标
for index,item in enumerate(verse):
if index%2==0:
print(item+",",end=" ")
else:
print(item+"。")
# 修改元组直接赋值即可
uku=uku+(12,34) # 添加直接在后面连接即可,但必须是元组,不能是其他东西
uku=uku+(1,)
# 元组推导式
ran=(random.randint(10,100) for i in range(10)) # 这时是一个生成器对象
ran=turple(ran)
ran=list(ran) # 需要什么就使用什么函数转化
number=(i for i in range(3))
print(number.__next__()) # 这是一种函数
print(number.__next__())
print(number.__next__())
number=tuple(number)
print("转换后:",number)
number=(i for i in range(4))
for i in number:
print(i,end="")
print(tuple(number))
# 字典
# 以上两种都是想再使用该遍历器对象,都必须新创建一个,遍历后原生成器对象就不存在了
# list与tuple的区别:1.前者是可变序列,后者是不可变序列。 2.前者可以使用增删改,后者只能切片,其余不行 3.如果只是想访问,建议用元组更快 4.列表不能当键,而后者可以
# python中字典相当于Map对象 关联数组,散列表,字典可以在原处增长或者缩短
# 字典键必须唯一,不然以最后一次的键值为准 键可以是数字,字符串,元组
# 字典的键不能是列表 typeError: unhashable type:'list'
# 字典对象的pop()方法删除并返回指定键的元素,以及字典对象的popitem()方法删除并返回字典中的一个元素。
dictionary={'key':'value','key2':'value',} # 值可以是任意数据类型,不一定要唯一
dic={}
dic=dict{} # 创建空字典
# 通过映射函数创建字典
dic=dict(zip(list1,list2)) #tuple(zip(,)) list(zip(,)) 可以转化
# zip(,)可以处理list,tuple 最后组合成tuple返回对象,长度不同取最小值
dic=dict(key1=value1,key2=value2,------,keyn=valuen) # 注意key不能是list
dic=dict(a='a',b='b')
dic=dict.fromkeys(list1) # 创建值为空的字典,list作为键输出{1=None,2=None}
# 创建字典
name_tuple=('1','2','3','4') #作为键的元组
sign=['1','2','3','4']
dict1={name_tuple:sign}
print(dict1)
{('1','2','3','4'):['1','2','3','4']} # 整体为字典
del dictionary
dictionary.clear() # 变成空字典
print(dictionary)
print(dictionary['冷依']) # 根据键输出值
print("我的",dictionary['12'] if '12' in dictionary else '我的字典里没有这个人')
dictionary.get(key,k) # 推荐方法,使用get方法获取指定键的值,指定键不存在时返回一个默认值
dictionary.get('tom','this dictionary has not this man')
person_dict=dict(zip(name,sign-person))
sign_dict.get(person_dict.get("Tom")) # Tom是什么星座->是什么性格
# 遍历字典
dictionary.items() # 返回值为可变历的值与键对的元组列表,下面这个就有三组元组列表
dictionary={'qq':'12','13':'as','qf':'qz'}
for item in dictionary.items():
print(item)
for key,value in dictionary.items():
print(key,"的联系电话是",value) #也可以使用values() keys() 方法,使用方法与items()类似
dictionary=dict(('12','34'),('34','56'))
dictionary['qw']='12' # 添加一个元素,当如果存在时,就相当于是修改功能
del dictionary['想你'] #删除,为了防止删除不存在的元素时抛出异常
if "12" in dictionary:
del dictionary["12"]
print(dictionary)
# 字典推导式
randomdict={i:random.randint(10,100) for i in range(1,5)} #???
dictionary ={i:j+'做' for i,j in zip(name,sign)}
print(dictionary)
# 集合
# 用来保存不重复的元素,可变集合:set 不可变集合:frozenset ,集合放在{} 里。
# 如果输入了重复的,就只保留一个
# 集合是无顺序的,每次输出的顺序可能与上次不同。
# 创建空集合时,不能使用一对大括号“{}”实现,那样只会创造一个空字典
# 创建集和推荐用set()函数实现
# del删除集合,pop() remove() clear() 使其变为空集合,而不是没有这个集合 '12' in c判断一下在不在再删除
# 集合交集& 并集| 差集- 对称差集^交集的补集
setname={element1,element2,~,}
setname =set(iteration) #iteration是可迭代对象,列表元组,range对象
set2 =set([1.414,1.732,3.1419,2.236])
set3=set(('12','34'))
set1=set("等哈时刻,生的伟大") # 其中的标点符号也要被分
setname.add(elemennt) # 这里只能使用字符串,数字与布尔类型的True与false ,不能使用列表,元组等可迭代对象
pythonjihe &|^ cjihe
#函数
#'''这是段注释,但可以当做参数被调用'''这个必须有一定注释
#如果函数什么也不做,则要用pass作为点位符,或者添加docstring
#函数名._defaults_查看函数的默认值参数,结果是一个元组
#可变参数也称为不定长参数:*parameter接受任意多个实际参数并将其放在一个元组中,**parameter
fun_bmi(height=1.83,weight=60,person="路人甲")#关键值参数
def fun(height,weight,person="路人甲")#如果没有传入参数时,可以直接使用定义函数时设置的默认值
put()
input()
def function(x1,x2):#没有参数时也要保存小括号,否则显示 invalid syntax
'''这是段注释,但可以当做参数被调用'''
return x1+x2
print(function._doc_)
help(function) #这两种就可以输出这段注释
pattern=r'(黑客)|(抓包)|(监听)|(trojan)'#模式字符串,????
sub=re.sub(pattern,'a_a',string)#进行模式替换
day=datetime.datetime.now().weekday() #获取当前日期
function_tips() #调用函数
def printcoffee(*coffeename):
print("\n我喜欢的咖啡有:")
for item in coffeename:
print(item)
#如果想使用一个已经存在的列表作为函数的可变参数,可以在列表的名称前面加"*"
printcoffee(*param)
#**parameter表示接受多个显式赋值,并放到一个字典中
def printsign(**sign):
print()
for key,value in sign.items():
print("["+key+"]的星座是"+value)
#如果想使用一个已经存在的字典,可以直接在字典前面加**
dct1={'1','2','3'}
printsign(**dct1)
#如果返回的是多个值,那么就是返回的元组
money_old=sum(money)
money_new='{:.2f}'.format(money_old*0.9)
return money_old,money_new
#如果在函数外部使用局部变量,会抛出NameError异常
#注意使用函数时一定要调用函数
#当重名时,对内部赋值不会对外部的变量有影响
def f_demo():
global message#在函数内部若这样使用就是全局的
message='1223'
print('函数内部:message=',message)
#匿名函数,lambda语句只能有一个返回值,那么就必须赋给一个变量,否则有乱码
result=lambda x:expression
def circlear(r):
result=math.pi*r*r
return result
result=lambda r:math.pi*r*r
bookinfo.sort(key=lambda x:(x[1],x[1]/x[2])) #按照指定规则排序
for list_person in person:
for item in list_person:
person=item[0]
height=item[1]
weight=item[2]
print("\n"+"="*13,person,"="*13)
print("身高:"+str(height)+"m\t 体重:"+str(weight+"kg"))
bmi=weight(height*height)
print("BMI指数:"+str(bmi))
# 判断体重是否合理
if bmi<18.5:
print("您的体重过轻")
if bmi>=18.5:
print("您的体重过重")
def demo(obj=None):
if obj==None:
obj=[]
print("obj的值",obj)
obj.append(1)
#第一次实验:
print("{}大哥".format(name[1:]))
print("{}大哥".format(name[:3]))
#保留两位小数
a=12.345
print("%.2f"%a)
print('{:.2f}'.format(a))
print(round(a,2))
a=eval(input())#转化为数值类型
#转换货币
a=input()
c=(eval(a[3:]))*6.4 #字符串通过eval转换为数值
d=(eval(a[3:]))/6.4
if a[0]=='U':
print("RMB"+str("%.2f" %c))
else:
print("USD"+str("%.2f" %d)) #在python中拼接必须是字符串
#第二次实验:
str=input()
if 'p' in str:
str=str.replace('p','P')
print(str.split(' '))#打印以此' '分隔的一系列字符串
print(str)
a=input()
b=a[::-1]#这个就是反转的好方法
if a.isdigit() and len(a)==5:
if(int(a)==int(b)):
print("True")
else :
print("False")
#第三次实验:
from math import pi as PI
def gcd(x,y):
c=0
while(x%y!=0):
c=x%y
x=y
y=c
return y
def lcm(a,b):
gc=gcd(a,b)
for i in range(1,10000):
lc=gc*i
if (lc%a==0 and lc%b==0):
return lc
for i in range(1,10):
output=""
for j in range(1,i+1):
if output !="":
output +=" "
output +="{}*{}={}".format(i,j,i*j)
print(output)
#python字符串直接等于判断,或者 import re re.match(unit,"cm")
#python可以连着比较<==>
#第四次实验
divmod(7,2) #返回商和余数(3,1)
max(2,6,1,7) #返回最大值
sum((1,2,3,4)) #返回10
sum([1,2,3,4],-10) #传入元素之和
bool(1) #返回参数的逻辑值
complex('2+4j') #返回(2+4j)
complex(1,2) #返回(2+4j)
all([1,2,3]) #判断可迭代对象是否每个元素都为True值
any([1,2,3]) #判断可迭代对象是否有True值
sorted(a) #排序,返回一个新的列表,不会改变原列表,是一个内置函数,并不是列表对象的一个方法
s.sort() #升序
s.sort(reverse=True) #降序
list1=list("hello") #任何可迭代对象都可以生成
list2=list(turple1)
list3=list(dictiona)
list4=list(range(1,6))
list5=list() #空列表
my_menu=input().split(",")
newli=li[start:end:step]
del #根据索引值删除
pop #同上
remove() #根据元素值进行删除
clear() #删除所有元素
#列表推导式
example=[i**2 for i in range(1,11) if i%2==0]
len(turple)
max(turple)
min(turple)
turple(turple) #将列表转化为元组,因为元组的元素不能改变,没有append(),insert(),但其他方法与列表获取是一样的
menu={'fish':'40','pork':'30'}
m1=menu['fish'] #可以这样访问
del menu['fish'] #字典定义dict()
for key,value in menu.items():
print(str(key)+str(value))
>>> dict(a='a', b='b', t='t') # 传入关键字
{'a': 'a', 'b': 'b', 't': 't'}
>>> dict(zip(['one', 'two', 'three'], [1, 2, 3])) # 映射函数方式来构造字典
{'three': 3, 'two': 2, 'one': 1}
>>> dict([('one', 1), ('two', 2), ('three', 3)]) # 可迭代对象方式来构造字典
{'three': 3, 'two': 2, 'one': 1}
for key in menu.keys():
menu2[key]=2*menu1[key]
for value in menu.values():
更多推荐



所有评论(0)