python基础1
来源:互联网 发布:房地产签单客源软件 编辑:程序博客网 时间:2024/05/29 12:53
pycharm快捷键
ctrl+d 复制行
ctrl+x 删除行
ctrl+/ 注释
''' 多行注释,只能用于模块头部
shift+↑或↓ 选择
shift+alt+↑或↓ 移动行
ctrl+alt+L 美化代码
tab 补全命令
在终端中执行py文件:python g:/test.py
1. 变量
name = "liming"
age = 25
print(name, "'age is ", age) #print()用来打印, ,用来连接
name,age="zhangsan",23
2. 常量
全部大写NAME='miling'
MYSQL_CONNECTION=""
3. name = 'Alex'
name2 = name
name = 'longmingwang'
print(name, name2)#longmingwang Alex
4. 在pycharm中文件->设置->editor->文件和代码模版中修改python script中添加#author xinwang
这样所有的新建python文件都会有这行注释
5. 在python2中
input:输入的数字就是数字,"alex"是文本,alex是变量
raw_input:输入全部是文本
在python3中
input:输入的全是文本
6. '''打印多行文本
7. 例子
name = input("please input your name:")
age = int(input("please input your age:"))
job = input("please input your job:")
msg = ('''information of user %s
---------------------------
name : %s
age : %d
job : %s''') % (name, name, age, job)
print(msg)
8. getpass:在pycharm中无效
1 >>> import getpass
2 >>> p=getpass.getpass('input your password')#输入密码时用getpass代替了input
3 input your password
4 >>> print(p)
5 aaa
9. os:在python中执行系统命令
import os
print(os.system("top"))
os.mkdir("/home/wangxin/test)
print(os.system("ls -l /"))
保存命令输出:rs=os.popen("df").read()
print(rs)
10.sys
import sys
print(sys.argv) #参数
print(sys.path)
11. if ... else
模拟登录:
user = 'alex'
passd = 'alex'
username = input("username:")
password = input("password:")
if username == user:
print("the username is correct...")
if password==passd:
print ("welcome to login")
else:
print("but your password is invalid")
else:
print("连用户名都没蒙对,滚粗!")
优化:
if username == user and passd==password:
print("welcome to login")
else:
print("your username or password is invalid!")
age=21
guessnum=int(input("guess age:"))
if age==guessnum :
print("got it! so smart!")
elif guessnum>age:
print("elder than age")
else:
print("smaller than age")
12. for i in 列表:
age=21
for i in range(10): #range(10)=[0,1,2,3,4,5,6,7,8,9]
guessnum=int(input("guess age:"))
if age==guessnum :
print("got it! so smart!")
break #不往后走了,跳出整个循环
elif guessnum>age:
print("elder than age")
else:
print("smaller than age")
13. 程序执行顺序
n = int(input("n="))
if n > 1:
print("n>1")
elif n > 2:
print("n>2")
else:
print("heha")
print("end")
结果:
n=8
n>1
end
14. 字符串格式化输出
name="liming"
print("I am %s" % name)
万恶的+:开辟多个内存空间
print("my name is "+name+"!")
15.列表====数组
age=9
name=["minglong","minghu","mingchong",3,age]
列表名[索引]
print(name[0]) #"minglong"
print(name[-1]) #age
只会从左到右取:
name[0:2] #["minglong","minghu"]
name[-3:-1]
name[:6]#前五个
name[:]全部
name[2:6][2:4][0][1]
赋值
name[1]="newname"
name.insert(2,"minggou")#在2元素前插入
name.append("alex")#在列表最后插入
删除:
name.remove("minggou")#删除找到的第一个为minggou的项
name.pop(7) #不加参数默认为-1
del #删除内存中的数据,全局使用
del student[4:6] #删除第4,5
del student #删除列表
步长:
student[0:8:2]
个数:
student.count("s2")
查找值:
判断是否存在: "s2" in student
student.index("s2")#找到的第一个s2的索引位置
eg:改掉里面所有的s4:
for i in range(student.count('s4')):
i=student.index("s4")
student[i]="444"
清空:
student.clear()
扩展:
student1.extend(student2)
反转:动作,无返回值
student.reverse()
排序:
student.sort()#python3中字符串和数字不能一块排序
复制:
copy:浅层复制
student2=student.copy()
eg:
student = [1, 2, 3, 4, [5, 7, 6, 5], 43, 32, 12]
student2 = student.copy()
student[0] = 54
print(student)
print(student2)
student[4][0]=64365464
print(student)
print(student2)
结果为:
[54, 2, 3, 4, [5, 7, 6, 5], 43, 32, 12]
[1, 2, 3, 4, [5, 7, 6, 5], 43, 32, 12]
[54, 2, 3, 4, [64365464, 7, 6, 5], 43, 32, 12]
[1, 2, 3, 4, [64365464, 7, 6, 5], 43, 32, 12]
deepcopy:深层复制
import copy
student2=copy.deepcopy(student)
eg:
import copy
student = [1, 2, 3, 4, [5, 7, 6, 5], 43, 32, 12]
student2 = student.copy()
student3 = copy.deepcopy(student)
student[0] = 54
print(student)
print(student2)
print(student3)
student[4][0]=64365464
print(student)
print(student2)
print(student3)
结果:[54, 2, 3, 4, [5, 7, 6, 5], 43, 32, 12]
[1, 2, 3, 4, [5, 7, 6, 5], 43, 32, 12]
[1, 2, 3, 4, [5, 7, 6, 5], 43, 32, 12]
[54, 2, 3, 4, [64365464, 7, 6, 5], 43, 32, 12]
[1, 2, 3, 4, [64365464, 7, 6, 5], 43, 32, 12]
[1, 2, 3, 4, [5, 7, 6, 5], 43, 32, 12]
长度:
len(student)
16.元组:不可修改
( )tuple
17.字符串
str.strip() ---删除两边空白-空格,tab
str.split() ---str没变,得到个列表
"|".join(['a','bc','1']) ---将列表中元素(必须都是字符串)用|拼成字符串 :a|bc|1
"".join(['a','b','c'])-->abc
"" in "alex li" ----判断空格
"1234".isdigit()----判断字符串是否是纯数字组成,True
'fe'.isalpha()----是不是字母
'feAFE'.isupper()----是不是全是大写
'fwef'.islower()----是不是全是小写
ord('c') -->99
chr(99) -->c
格式化:format
msg = "name={0},age={1}"
print(msg.format('liming', 27))
"alex".center(40,"-") #------------------alex------------------
"alex".find("ex")#2,返回所引
print("abcd".endswith("d")) #True
print("abcd".startswith("a"))#True
字符串是列表:
for i in 'abcd':
print(i)
eg:生成六位验证码:
import random
yanzhengma=[]
for i in range(6):
jj=random.randrange(0,2)
if jj==0:#数字
temp=random.randrange(0,10)
yanzhengma.append(str(temp))
else:
temp=random.randrange(65,91)
r=chr(temp)
yanzhengma.append(r)
yanzhengma="".join(yanzhengma)
print(yanzhengma)
18. 数据运算
% -----除法的余数,判断正奇数
// -----商的整数部分
!= -----不等于
== -----等于
赋值:左边一定是变量
= -----赋值
+= -----相加;c+=a-->c=a+c
-=
and
or
not
位运算:计算机中能存储,表示的最小单位,是一个二进制位
byte(字节)=8bit
1kbyte=1024byte
1Mbyte=1024kbyte
1Gbyte=1024Mbyte
1 1 1 0 1 1=60
0 0 1 1 0 1=13
60 & 13 =12 ---按位与运算
60 | 13 =61 ---按位或运算
60 ^ 13=49 ---按位异或
~60=195-256=-61 ---按位取反
64<<1=128 左移1位
64>>1=32 右移1位
19.死循环
while True
i = 0
while True:
i += 1
if i>50 and i<60:
continue
print("i=", i)
if i==100:
print("fuck!!!")
break
20.字典{}:无序
d={key1:value1,key2:value2,key3:value3}
d[key2]=value_2_new
eg:
d = {
"001": {
"name": "liming",
"age": 25,
"address": "henan"},
"002": {
"name": "zhangsan",
"age": 65,
"address": "yongxia"},
"003": {
"name":"lisi",
"age":85,
"address":"jinan"
}
}
d["002"].pop("age") --->删除age:65
print (d["002"]["age"])
取出所有的keys列表
d.keys()
取出所有的values列表
d.values()
判断key是否存在
"003" in d ---->True
循环
for key in d:
print(key)
print(d[key])
取值不抱错: d[]可能会报错
setdefault:存在时就直接取出(相当于get),没有就设置默认值后取出
print(d.setdefault("003",{"name":"sim"}))
get: d.get("003")
删除:
d.pop(key)
d.popitem() -->随机删除
21. 退出程序
exit("sorry")
打印出列表中索引号:
for i in enumerate(range(5)):
print(i)
结果为:
(0, 0)
(1, 1)
(2, 2)
(3, 3)
(4, 4)
22.set集合---无序,不可重复
创建:
s={123,456,789,852,46}
s=set([])#调用了构造函数__init__
添加元素:
add:
s.add(123)
update:列表或元组或字符串;for循环加入
s.update([1,2,3])#一次添加多个元素
s.update("abcdabcd")#新增了'a','b','c','d'
清空:
s.clear()
差异:
s.different(s1)#s中存在,s1中不存在
s1.symmetric_difference(s)#并集中去掉交集
差异更新:
s.different(s1)#求差异更新到s中
s1.symmetric_difference_update(s)
移除:
remove:
s.remove(111)#不存在时会报错
discard:
s.discard(123)#即使不存在也不会报错
pop:
s.pop() #随机删除,不建议使用
交集:
s.intersection(s1)
s.intersection_update(s1)
并集:
s.union(s1)
23.函数,在py文件中可直接定义,不需要一定在class中定义,参数传的是引用
默认参数:
def fun1(x,y,z='ok'):
print (x,y,z)
return x+y #没有return时默认是none
print() #不会被执行
调用:fun1(2,3,'ss') #2 3 'ss'
fun1(2,3) #2,3,'ok'
动态参数:
*args,将传进来的参数放在一个元祖中
eg:
def ff(*args):
print(args)
ff("nilian","hello","world") #args=('nilian', 'hello', 'world')
ff(("nilian","hello","world")) #args=(('nilian', 'hello', 'world'))
ff(["nilian","hello","world"]) #args=(['nilian', 'hello', 'world'])
循环的放进元祖中:
ff(*"hello") #args=('h', 'e', 'l', 'l', 'o') <class 'tuple'>
ff(*("hello","world")) #args=('hello', 'world') <class 'tuple'>
ff(*["hello","world"]) #args=('hello', 'world') <class 'tuple'>
**args:将传进来的参数放在字典中
def ff(**args):
print(args,type(args))
参数:变量=''
ff(name="liming",age=21) #args={'name': 'liming', 'age': 21} <class 'dict'>
参数:**{字典}
ff(**{'name':"liming"}) #args={'name':'liming'} <class 'dict'>
万能参数:
def f(*args,**args):
f(1,2,3,name='zhangsan',age=21)
字符串有个函数:format(*args,**args)
全局变量:大写
任何作用域都能访问
修改全局变量,先:声明global 变量名 再:变量名=''
python是面向函数编程.封装到函数,
内置函数:
abs:绝对值
bool():0,None,False,"",(),[],{}为False
all():全为True,才为True,如all([1,2,None])为假
any():有一个True,就为True,如any([1,2,None])为真
bin():二进制0b
oct():八进制0o
hex():十六进制0x
utf-8:一个汉字三个字节,一个字母一个字节
gbk:一个汉字两个字节,一个字母一个字节
bytes():转化为字节,如bytes('lisa啊',encoding='utf-8')-->b'lisa\xe5\x95\x8a' ,a-z不变,0-9不变,汉字会转化为3个字节,每个字节为两个十六进制
str():str(b'lisa\xe5\x95\x8a',encoding='utf-8')-->'lisa啊' .字节转化为字符串
操作文件
打开文件:f=open('db','r',[encoding='utf-8']) #只读,读的是字符串,乱码时要写对encoding
f=open('db','rb') #以二进制读取,
f=open('db','w') #只写,先清空
f=open('db','wb') #以二进制写入,f.write(bytes('lisa',encoding='utf-8'))
f=open('db','x') #文件存在则报错,不存在,则创建并写内容
f=open('db','a') #追加,可读,不存在则创建,存在则只追加内容
+:可以同时读写:
f.seek(1) #按字节调整读指针,跳过一个字节,有汉字(三个字节)会乱码)
f.tell() #获取现在指针位置,一个汉字为三个字节
f=open('db','r+') #读写,可读可写,因为读导致指针移到最后了,所以write在末尾(追加)
f=open('db','w+') #写读,可读可写
f=open('db','x+') #写读,可读可写
f=open('db','a+') #写读,可读可写
eg:
f=open('db','r+',encoding='utf-8')
r=f.read(1) #汉字
print(r)
p=f.tell() #3
f.seek(p)
f.write('lisi|35252')
f.close()
操作文件:
f.read():读取,指针随着移动,无参数读全部,有参数时看打开方式:
r:按字符读,
rb:按字节读
write():写入,wb时写入字节
flush():将修改flush到磁盘
readable():w模式打开时False
readline():读取一行,指针随着一行
truncate():截断文件,指针后清空
for line in f:一行一行的读取文件
关闭文件:f.close()
with open('db','r') as f,open('db1','r') as f2:
pass
pass
compile:将字符串编译成python代码,eval,exec来执行代码
s="print(4)"
r=compile(s,'<string>','exec')
exec(r)
exec:执行python代码,没有返回值,接收代码或字符串
exec("print(23)")--->23
eval:执行表达式运算,并返回值
eval("print(23)")--->23,并返回None
eval('8*8') ---->返回64
dir:查看对象提供了什么功能
divmod:得到商和余数,返回元组(商,余数)
isinstance:判断对象是不是类的实例
l=[]
r=isinstance(l,dict)
print(r) -->False
类:str,dict,list
str的实例:"alex"
dict的实例:{}
list的实例:[]
24. import
import math:math是.py文件,里面有def函数例如sqrt,还有class
from math import sqrt:从math文件中引入def sqrt.
25.ascii和字符转换
ctrl+d 复制行
ctrl+x 删除行
ctrl+/ 注释
''' 多行注释,只能用于模块头部
shift+↑或↓ 选择
shift+alt+↑或↓ 移动行
ctrl+alt+L 美化代码
tab 补全命令
在终端中执行py文件:python g:/test.py
1. 变量
name = "liming"
age = 25
print(name, "'age is ", age) #print()用来打印, ,用来连接
name,age="zhangsan",23
2. 常量
全部大写NAME='miling'
MYSQL_CONNECTION=""
3. name = 'Alex'
name2 = name
name = 'longmingwang'
print(name, name2)#longmingwang Alex
4. 在pycharm中文件->设置->editor->文件和代码模版中修改python script中添加#author xinwang
这样所有的新建python文件都会有这行注释
5. 在python2中
input:输入的数字就是数字,"alex"是文本,alex是变量
raw_input:输入全部是文本
在python3中
input:输入的全是文本
6. '''打印多行文本
7. 例子
name = input("please input your name:")
age = int(input("please input your age:"))
job = input("please input your job:")
msg = ('''information of user %s
---------------------------
name : %s
age : %d
job : %s''') % (name, name, age, job)
print(msg)
8. getpass:在pycharm中无效
1 >>> import getpass
2 >>> p=getpass.getpass('input your password')#输入密码时用getpass代替了input
3 input your password
4 >>> print(p)
5 aaa
9. os:在python中执行系统命令
import os
print(os.system("top"))
os.mkdir("/home/wangxin/test)
print(os.system("ls -l /"))
保存命令输出:rs=os.popen("df").read()
print(rs)
10.sys
import sys
print(sys.argv) #参数
print(sys.path)
11. if ... else
模拟登录:
user = 'alex'
passd = 'alex'
username = input("username:")
password = input("password:")
if username == user:
print("the username is correct...")
if password==passd:
print ("welcome to login")
else:
print("but your password is invalid")
else:
print("连用户名都没蒙对,滚粗!")
优化:
if username == user and passd==password:
print("welcome to login")
else:
print("your username or password is invalid!")
age=21
guessnum=int(input("guess age:"))
if age==guessnum :
print("got it! so smart!")
elif guessnum>age:
print("elder than age")
else:
print("smaller than age")
12. for i in 列表:
age=21
for i in range(10): #range(10)=[0,1,2,3,4,5,6,7,8,9]
guessnum=int(input("guess age:"))
if age==guessnum :
print("got it! so smart!")
break #不往后走了,跳出整个循环
elif guessnum>age:
print("elder than age")
else:
print("smaller than age")
13. 程序执行顺序
n = int(input("n="))
if n > 1:
print("n>1")
elif n > 2:
print("n>2")
else:
print("heha")
print("end")
结果:
n=8
n>1
end
14. 字符串格式化输出
name="liming"
print("I am %s" % name)
万恶的+:开辟多个内存空间
print("my name is "+name+"!")
15.列表====数组
age=9
name=["minglong","minghu","mingchong",3,age]
列表名[索引]
print(name[0]) #"minglong"
print(name[-1]) #age
只会从左到右取:
name[0:2] #["minglong","minghu"]
name[-3:-1]
name[:6]#前五个
name[:]全部
name[2:6][2:4][0][1]
赋值
name[1]="newname"
name.insert(2,"minggou")#在2元素前插入
name.append("alex")#在列表最后插入
删除:
name.remove("minggou")#删除找到的第一个为minggou的项
name.pop(7) #不加参数默认为-1
del #删除内存中的数据,全局使用
del student[4:6] #删除第4,5
del student #删除列表
步长:
student[0:8:2]
个数:
student.count("s2")
查找值:
判断是否存在: "s2" in student
student.index("s2")#找到的第一个s2的索引位置
eg:改掉里面所有的s4:
for i in range(student.count('s4')):
i=student.index("s4")
student[i]="444"
清空:
student.clear()
扩展:
student1.extend(student2)
反转:动作,无返回值
student.reverse()
排序:
student.sort()#python3中字符串和数字不能一块排序
复制:
copy:浅层复制
student2=student.copy()
eg:
student = [1, 2, 3, 4, [5, 7, 6, 5], 43, 32, 12]
student2 = student.copy()
student[0] = 54
print(student)
print(student2)
student[4][0]=64365464
print(student)
print(student2)
结果为:
[54, 2, 3, 4, [5, 7, 6, 5], 43, 32, 12]
[1, 2, 3, 4, [5, 7, 6, 5], 43, 32, 12]
[54, 2, 3, 4, [64365464, 7, 6, 5], 43, 32, 12]
[1, 2, 3, 4, [64365464, 7, 6, 5], 43, 32, 12]
deepcopy:深层复制
import copy
student2=copy.deepcopy(student)
eg:
import copy
student = [1, 2, 3, 4, [5, 7, 6, 5], 43, 32, 12]
student2 = student.copy()
student3 = copy.deepcopy(student)
student[0] = 54
print(student)
print(student2)
print(student3)
student[4][0]=64365464
print(student)
print(student2)
print(student3)
结果:[54, 2, 3, 4, [5, 7, 6, 5], 43, 32, 12]
[1, 2, 3, 4, [5, 7, 6, 5], 43, 32, 12]
[1, 2, 3, 4, [5, 7, 6, 5], 43, 32, 12]
[54, 2, 3, 4, [64365464, 7, 6, 5], 43, 32, 12]
[1, 2, 3, 4, [64365464, 7, 6, 5], 43, 32, 12]
[1, 2, 3, 4, [5, 7, 6, 5], 43, 32, 12]
长度:
len(student)
16.元组:不可修改
( )tuple
17.字符串
str.strip() ---删除两边空白-空格,tab
str.split() ---str没变,得到个列表
"|".join(['a','bc','1']) ---将列表中元素(必须都是字符串)用|拼成字符串 :a|bc|1
"".join(['a','b','c'])-->abc
"" in "alex li" ----判断空格
"1234".isdigit()----判断字符串是否是纯数字组成,True
'fe'.isalpha()----是不是字母
'feAFE'.isupper()----是不是全是大写
'fwef'.islower()----是不是全是小写
ord('c') -->99
chr(99) -->c
格式化:format
msg = "name={0},age={1}"
print(msg.format('liming', 27))
"alex".center(40,"-") #------------------alex------------------
"alex".find("ex")#2,返回所引
print("abcd".endswith("d")) #True
print("abcd".startswith("a"))#True
字符串是列表:
for i in 'abcd':
print(i)
eg:生成六位验证码:
import random
yanzhengma=[]
for i in range(6):
jj=random.randrange(0,2)
if jj==0:#数字
temp=random.randrange(0,10)
yanzhengma.append(str(temp))
else:
temp=random.randrange(65,91)
r=chr(temp)
yanzhengma.append(r)
yanzhengma="".join(yanzhengma)
print(yanzhengma)
18. 数据运算
% -----除法的余数,判断正奇数
// -----商的整数部分
!= -----不等于
== -----等于
赋值:左边一定是变量
= -----赋值
+= -----相加;c+=a-->c=a+c
-=
and
or
not
位运算:计算机中能存储,表示的最小单位,是一个二进制位
byte(字节)=8bit
1kbyte=1024byte
1Mbyte=1024kbyte
1Gbyte=1024Mbyte
1 1 1 0 1 1=60
0 0 1 1 0 1=13
60 & 13 =12 ---按位与运算
60 | 13 =61 ---按位或运算
60 ^ 13=49 ---按位异或
~60=195-256=-61 ---按位取反
64<<1=128 左移1位
64>>1=32 右移1位
19.死循环
while True
i = 0
while True:
i += 1
if i>50 and i<60:
continue
print("i=", i)
if i==100:
print("fuck!!!")
break
20.字典{}:无序
d={key1:value1,key2:value2,key3:value3}
d[key2]=value_2_new
eg:
d = {
"001": {
"name": "liming",
"age": 25,
"address": "henan"},
"002": {
"name": "zhangsan",
"age": 65,
"address": "yongxia"},
"003": {
"name":"lisi",
"age":85,
"address":"jinan"
}
}
d["002"].pop("age") --->删除age:65
print (d["002"]["age"])
取出所有的keys列表
d.keys()
取出所有的values列表
d.values()
判断key是否存在
"003" in d ---->True
循环
for key in d:
print(key)
print(d[key])
取值不抱错: d[]可能会报错
setdefault:存在时就直接取出(相当于get),没有就设置默认值后取出
print(d.setdefault("003",{"name":"sim"}))
get: d.get("003")
删除:
d.pop(key)
d.popitem() -->随机删除
21. 退出程序
exit("sorry")
打印出列表中索引号:
for i in enumerate(range(5)):
print(i)
结果为:
(0, 0)
(1, 1)
(2, 2)
(3, 3)
(4, 4)
22.set集合---无序,不可重复
创建:
s={123,456,789,852,46}
s=set([])#调用了构造函数__init__
添加元素:
add:
s.add(123)
update:列表或元组或字符串;for循环加入
s.update([1,2,3])#一次添加多个元素
s.update("abcdabcd")#新增了'a','b','c','d'
清空:
s.clear()
差异:
s.different(s1)#s中存在,s1中不存在
s1.symmetric_difference(s)#并集中去掉交集
差异更新:
s.different(s1)#求差异更新到s中
s1.symmetric_difference_update(s)
移除:
remove:
s.remove(111)#不存在时会报错
discard:
s.discard(123)#即使不存在也不会报错
pop:
s.pop() #随机删除,不建议使用
交集:
s.intersection(s1)
s.intersection_update(s1)
并集:
s.union(s1)
23.函数,在py文件中可直接定义,不需要一定在class中定义,参数传的是引用
默认参数:
def fun1(x,y,z='ok'):
print (x,y,z)
return x+y #没有return时默认是none
print() #不会被执行
调用:fun1(2,3,'ss') #2 3 'ss'
fun1(2,3) #2,3,'ok'
动态参数:
*args,将传进来的参数放在一个元祖中
eg:
def ff(*args):
print(args)
ff("nilian","hello","world") #args=('nilian', 'hello', 'world')
ff(("nilian","hello","world")) #args=(('nilian', 'hello', 'world'))
ff(["nilian","hello","world"]) #args=(['nilian', 'hello', 'world'])
循环的放进元祖中:
ff(*"hello") #args=('h', 'e', 'l', 'l', 'o') <class 'tuple'>
ff(*("hello","world")) #args=('hello', 'world') <class 'tuple'>
ff(*["hello","world"]) #args=('hello', 'world') <class 'tuple'>
**args:将传进来的参数放在字典中
def ff(**args):
print(args,type(args))
参数:变量=''
ff(name="liming",age=21) #args={'name': 'liming', 'age': 21} <class 'dict'>
参数:**{字典}
ff(**{'name':"liming"}) #args={'name':'liming'} <class 'dict'>
万能参数:
def f(*args,**args):
f(1,2,3,name='zhangsan',age=21)
字符串有个函数:format(*args,**args)
全局变量:大写
任何作用域都能访问
修改全局变量,先:声明global 变量名 再:变量名=''
python是面向函数编程.封装到函数,
内置函数:
abs:绝对值
bool():0,None,False,"",(),[],{}为False
all():全为True,才为True,如all([1,2,None])为假
any():有一个True,就为True,如any([1,2,None])为真
bin():二进制0b
oct():八进制0o
hex():十六进制0x
utf-8:一个汉字三个字节,一个字母一个字节
gbk:一个汉字两个字节,一个字母一个字节
bytes():转化为字节,如bytes('lisa啊',encoding='utf-8')-->b'lisa\xe5\x95\x8a' ,a-z不变,0-9不变,汉字会转化为3个字节,每个字节为两个十六进制
str():str(b'lisa\xe5\x95\x8a',encoding='utf-8')-->'lisa啊' .字节转化为字符串
操作文件
打开文件:f=open('db','r',[encoding='utf-8']) #只读,读的是字符串,乱码时要写对encoding
f=open('db','rb') #以二进制读取,
f=open('db','w') #只写,先清空
f=open('db','wb') #以二进制写入,f.write(bytes('lisa',encoding='utf-8'))
f=open('db','x') #文件存在则报错,不存在,则创建并写内容
f=open('db','a') #追加,可读,不存在则创建,存在则只追加内容
+:可以同时读写:
f.seek(1) #按字节调整读指针,跳过一个字节,有汉字(三个字节)会乱码)
f.tell() #获取现在指针位置,一个汉字为三个字节
f=open('db','r+') #读写,可读可写,因为读导致指针移到最后了,所以write在末尾(追加)
f=open('db','w+') #写读,可读可写
f=open('db','x+') #写读,可读可写
f=open('db','a+') #写读,可读可写
eg:
f=open('db','r+',encoding='utf-8')
r=f.read(1) #汉字
print(r)
p=f.tell() #3
f.seek(p)
f.write('lisi|35252')
f.close()
操作文件:
f.read():读取,指针随着移动,无参数读全部,有参数时看打开方式:
r:按字符读,
rb:按字节读
write():写入,wb时写入字节
flush():将修改flush到磁盘
readable():w模式打开时False
readline():读取一行,指针随着一行
truncate():截断文件,指针后清空
for line in f:一行一行的读取文件
关闭文件:f.close()
with open('db','r') as f,open('db1','r') as f2:
pass
pass
compile:将字符串编译成python代码,eval,exec来执行代码
s="print(4)"
r=compile(s,'<string>','exec')
exec(r)
exec:执行python代码,没有返回值,接收代码或字符串
exec("print(23)")--->23
eval:执行表达式运算,并返回值
eval("print(23)")--->23,并返回None
eval('8*8') ---->返回64
dir:查看对象提供了什么功能
divmod:得到商和余数,返回元组(商,余数)
isinstance:判断对象是不是类的实例
l=[]
r=isinstance(l,dict)
print(r) -->False
类:str,dict,list
str的实例:"alex"
dict的实例:{}
list的实例:[]
24. import
import math:math是.py文件,里面有def函数例如sqrt,还有class
from math import sqrt:从math文件中引入def sqrt.
25.ascii和字符转换
0 0
- python(1) python基础
- Python基础篇1
- Python 基础 1
- python基础1
- Python基础汇总(1)
- Python 基础笔记(1)
- python基础笔记1
- python基础[1]
- python程序设计:基础1
- python基础 1: string
- Python Pandas基础1
- python基础1
- python学习1-基础
- Python 基础1
- Python基础1--数据类型
- Python 基础语法(1)
- python基础(1)
- python基础(1)
- Linux常用操作
- Java中如何解决double和float精度不准的问题
- nginx(8)
- 【腾讯云的1001种玩法】几种在腾讯云建立WordPress的方法(Linux)(二)
- selenium+Python+unittest运行启动jar包服务:
- python基础1
- 2017项目总结之123
- Apache Struts2 曝任意代码执行漏洞 (S2-045,CVE-2017-5638)
- 【LeetCode】50. Pow(x, n)
- Linux的gcc和g++的版本切换问题
- 来谈一谈数据可视化技术的误区——润乾软件
- Maven 创建springMvc项目
- BZOJ2023/1630: [Usaco2005 Nov]Ant Counting 数蚂蚁
- Nginx连七八糟配置