python 笔记
2.x 默认编码 ASSIC
gbk(encode/decode)--unicode--(encode/decode)utf-8
3.x 默认编码 文件UTF-8 字符unicode 即支持中文 python2 vs python3 默认支持中文 不兼容2.x 核心语法调整 新特性默认只有3.x上有 变量 stuNumber 常量 大写 a=501 b=a a=502 b==>501 del 删除变量,而不是数据,解除引用 字符编码 ASCII 255个符号 1字节 1980 GB2312 72*94=6768 中文支持 1995 GBK1.0 中文支持 2000 GB18030 中文支持 big5 台湾 unicode 万国码 2**16=65535 所有国家地区编码 统一2字节 UTF-8 unicode的扩展集,可变长的字符编码集 注释 # 单行注释 ''' ''' ("""也可) 多行注释 (打印多行)
'和"" 在python中意义一样
msg="hello,it's me"
msg='hello,it's me' 错误
==〉如果都有可以用三引号
centos6.5 安装python3.5 1、CentOS6.5 安装Python 的依赖包 yum groupinstall "Development tools" yum install zlib-devel bzip2-devel openssl-devel ncurses-devel sqlite-devel readline-devel tk-devel gdbm-devel db4-devel libpcap-devel xz-devel 2、下载Python3.5的源码包并编译 wget https://www.python.org/ftp/python/3.5.0/Python-3.5.0.tgz tar xf Python-3.5.0.tgz cd Python-3.5.0 ./configure --prefix=/usr/local --enable-shared make make install ln -s /usr/local/bin/python3 /usr/bin/python3 3、在运行Python之前需要配置库: echo /usr/local/lib >> /etc/ld.so.conf.d/local.conf ldconfig 4、运行演示: python3 --version Python 3.5.0 5、设置别名方便使用 alias py=python3
列表 a=['Tom','Ketty','Jerry','Timo','gtms'] >>> a[0] 'Tom' >>> a[1:4] ['Ketty', 'Jerry', 'Timo'] #取到下标为123的,顾头不顾尾 >>> a[0:] ['Tom', 'Ketty', 'Jerry', 'Timo', 'gtms'] >>> a[0:-1] ['Tom', 'Ketty', 'Jerry', 'Timo'] >>> a[0:-2] ['Tom', 'Ketty', 'Jerry'] >>> a[0:10] #hoho ['Tom', 'Ketty', 'Jerry', 'Timo', 'gtms'] >>> a ['Tom', 'Ketty', 'Jerry', 'Timo', 'gtms'] >>> a=['Tom', 'Ketty', 'Jerry', 'Timo', 'gtms'] >>> a[0:2]=["a","b"] >>> a ['a', 'b', 'Jerry', 'Timo', 'gtms'] >>> type(a) <type 'list'> 步长 >>> a[0:4] ['Tom', 'Ketty', 'Jerry', 'Timo'] >>> a[0:4:2] #步长 ['Tom', 'Jerry'] 反 >>> a[-1:1:-1] ['gtms', 'Timo', 'Jerry'] >>> b=a[0:3] >>> b ['Tom', 'Ketty', 'Jerry'] 列表方法append/insert >>> a.append("Jony") >>> a ['Tom', 'Ketty', 'Jerry', 'Timo', 'gtms', 'Jony'] >>> a.insert(3,"gongli") >>> a ['Tom', 'Ketty', 'Jerry', 'gongli', 'Timo', 'gtms', 'Jony'] 替换 >>> a[0]="dog" >>> a ['dog', 'Ketty', 'Jerry', 'gongli', 'Timo', 'gtms', 'Jony'] >>> a[0:2]=["a","b"] >>> a ['a', 'b', 'Jerry', 'gongli', 'Timo', 'gtms', 'Jony'] 删除remove/pop/del >>> a.remove("a") >>> a ['b', 'Jerry', 'gongli', 'Timo', 'gtms', 'Jony'] >>> a.remove("b") >>> a ['Jerry', 'gongli', 'Timo', 'gtms', 'Jony'] >>> a.remove(a[0]) >>> a ['gongli', 'Timo', 'gtms', 'Jony'] >>> a.pop(0) 'gongli' >>> a ['Timo', 'gtms', 'Jony'] >>> b=a.pop(0) >>> b 'Timo' >>> >>> del a[0] >>> a ['Jony'] >>> del a >>> a Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'a' is not defined count 统计某个元素在列表中出现的次数 >>> a ['hello', 'gtms', 'world', 'hello', 'gtms'] >>> a.count("gtms") 2 extend 扩展列表,而+操作,会返回一个全新的列表 >>> b ['1', '2', '1'] >>> a ['hello', 'gtms', 'world', 'hello', 'gtms', '1', '2', '1'] index 在列表中取出匹配项的第一个索引位置 ['hello', 'gtms', 'world', 'hello', 'gtms', '1', '2', '1'] >>> a.index("gtms") 1 >>> a ['1', '2', '1', 'gtms', 'hello', 'world', 'gtms', 'hello'] >>> first_gtms_index=a.index("gtms") >>> little_list=a[first_gtms_index+1:] >>> second_gtms_index=little_list.index("gtms") >>> first_gtms_index+second_gtms_index+1 6 reverse 将列表元素反向,list会变 >>> a ['1', '2', '1', 'gtms', 'hello', 'world', 'gtms', 'hello'] >>> a.reverse() >>> a ['hello', 'gtms', 'world', 'hello', 'gtms', '1', '2', '1'] sort 排序 >>> a.sort() >>> a ['1', '1', '2', 'gtms', 'gtms', 'hello', 'hello', 'world'] >>> a.sort(reverse=True) >>> a ['world', 'hello', 'hello', 'gtms', 'gtms', '2', '1', '1']
>>> b=sorted(a)
>>> b
['1', '1', '2', 'gtms', 'gtms', 'hello', 'hello', 'world']
列表嵌套 >>> a=[[1,2,3],"gtms",4,(4,5,6)] >>> b=a[0] >>> b [1, 2, 3] >>> a[0][0] 1 >>> a[3][0] 4
字符串 >>> print ("hello"*3) hellohellohello >>> print ("helloworld"[2:4]) ll >>> print ("or" in "helloworld") True >>> print ("%s is a good man" %"gtms") gtms is a good man >>> print ("a","b") a b >>> print ("a"+"b") ==〉会开辟2个内存块,一般不用加号拼 ab >>> print ("a"-"b") Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unsupported operand type(s) for -: 'str' and 'str' [root@node206 code]# cat test.py print ("hello world",end=" ") print ("hello world") [root@node206 code]# python3 test.py hello world hello world >>> a="gtms" >>> b="is" >>> c="a" >>> d="man" >>> print (a+b+c+d) gtmsisaman >>> e="".join([a,b,c,d]) >>> e 'gtmsisaman' >>> e="**".join([a,b,c,d]) >>> e 'gtms**is**a**man' >>> e="/".join([a,b,c,d]) >>> e 'gtms/is/a/man' 内置方法 >>> st="hello kitty" >>> st.count("l") 2 >>> st.capitalize() 'Hello kitty' >>> st.center() Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: center() takes at least 1 argument (0 given) >>> st.center(50,"-") '-------------------hello kitty--------------------' >>> st.endwith("tty") Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'str' object has no attribute 'endwith' >>> st.endswith("tty") True >>> st.startwith("he") Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'str' object has no attribute 'startwith' >>> st.startswith("he") True >>> sst="hello k\titty" >>> sst.expandtabs(tabsize=10) 'hello k itty' >>> st.find(t) Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 't' is not defined >>> st.find("t") 8 >>> st.find("tt") 8 >>> st.find("ty") 9 >>> sst="hello titty {name}" >>> st.format(name="gtms") 'hello kitty' >>> sst.find("ty") 9 >>> print (sst.format(name="gtms") ... ) hello titty gtms >>> sst="hello titty {name} {age}" >>> sst.format(name="gtms",age-36) File "<stdin>", line 1 SyntaxError: positional argument follows keyword argument >>> sst.format(name="gtms",age=36) 'hello titty gtms 36' >>> sst.format_map({"name":"gtms","age"=36}) File "<stdin>", line 1 sst.format_map({"name":"gtms","age"=36}) ^ SyntaxError: invalid syntax >>> sst.format_map({"name":"gtms","age":36}) 'hello titty gtms 36' >>> sst 'hello titty {name} {age}' >>> st.index("ty") 9 >>> st.isalnum() False >>> "aaa".isalnum() True >>> "aaa".isdecimal() False >>> "666".isdecimal() True >>> "0101".isdecimal() True >>> "0101".isdigit() True >>> "125.66".isdigit() False >>> "0101".isnumber() Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'str' object has no attribute 'isnumber' >>> "0101".isnumeric() True >>> "123".isidentifier() False >>> "abc".isidentifier() True >>> "aBc".islower() False >>> "aBc".isupper() False >>> "ABc".isupper() False >>> "ABc c".isspace() False >>> " ".isspace() True >>> "".isspace() False >>> "ABc c".istitle() False >>> "ABc C".istitle() False >>> "Ac C".istitle() True >>> "Ac C".lower() 'ac c' >>> "Ac C".upper() 'AC C' >>> "Ac C".swapcase() 'aC c' >>> "Ac C".ljust(50,“?”) File "<stdin>", line 1 "Ac C".ljust(50,“*”) ^ SyntaxError: invalid character in identifier >>> "Ac C".ljust(50,"*") File "<stdin>", line 1 "Ac C".ljus,"*") ^ SyntaxError: invalid syntax >>> "Ac C".ljust(50,"*" File "<stdin>", line 1 "Ac C".ljust(50"*" ^ SyntaxError: invalid syntax >>> "Ac C".ljust(50,"*" ... ) 'Ac C**********************************************' >>> "Ac C".rjust(50,"*") '**********************************************Ac C' >>> " Ac C ".str(50,"*") Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'str' object has no attribute 'str' >>> " Ac C ".strip() 'Ac C' >>> "\tAc C\n ".strip() 'Ac C' >>> "\tAc C\n ".lstrip() 'Ac C\n ' >>> "\tAc C\n ".rstrip() '\tAc C' >>>
用户输入 [root@node206 code]# cat test.py dethage=100 name=input("your name:") age=input("your age:") print (name,age) print ("only left:",dethage-int(age),"years") print ("only left:",str(dethage-int(age)),"years") print ("dethage type:",type(dethage)) print ("age type:",type(age)) [root@node206 code]# python3 test.py your name:root your age:33 root 33 only left: 67 years only left: 67 years dethage type: <class 'int'> age type: <class 'str'> #######input的内容为字符串
if语句
if express:
statement
猜年龄(注意缩进,官方建议4个空格) [root@node206 code]# cat test.py hisage=100 guess_age=int(input(">>:")) if guess_age==hisage: print ("right") elif guess_age>hisage: print ("bigger") else: print ("small")
[root@node206 code]# python3 test.py >>:100 right [root@node206 code]# python3 test.py >>:99 small [root@node206 code]# python3 test.py >>:101 bigger
#多个elif的情况,找到第一个即结束
三个数比大小 [root@node206 code]# cat test.py num1=input("num1=:") num2=input("num2=:") num3=input("num3=:") max_num =0 if num1>num2: max_num = num1 if max_num > num3: print("Max NUM is",max_num) else: print("Max NUM is",num3) else: max_num = num2 if max_num > num3: print("Max NUM is",max_num) else: print("Max NUM is",num3) [root@node206 code]# python3 test.py num1=:66 num2=:99 num3=:77 Max NUM is 99
算术运算符 : + - * / //(取整除) %(取余) ** 赋值运算符: = 、+= -= *= /= %= //= **= >>> num = 2 >>> num += 1 # 等价于 num = num + 1 >>> num -= 1 # 等价于 num = num - 1 >>> num *= 1 # 等价于 num = num * 1 >>> num /= 1 # 等价于 num = num / 1 >>> num //= 1 # 等价于 num = num // 1 >>> num %= 1 # 等价于 num = num % 1 >>> num **= 2 # 等价于 num = num ** 2 比较运算符:>、 <、 >=、 <=、 ==、!= True False >>> a = 5 >>> b = 3 >>> a > b # 检查左操作数的值是否大于右操作数的值,如果是,则条件成立。 True >>> a < b # 检查左操作数的值是否小于右操作数的值,如果是,则条件成立。 False >>> a <= b # 检查左操作数的值是否小于或等于右操作数的值,如果是,则条件成立。 False >>> a >= b # 检查左操作数的值是否大于或等于右操作数的值,如果是,则条件成立。 True >>> a == b # 检查,两个操作数的值是否相等,如果是则条件变为真。 False >>> a != b # 检查两个操作数的值是否相等,如果值不相等,则条件变为真。 True 逻辑运算符: not 、and、 or >>> a > b and a < b # 如果两个操作数都是True,那么结果为True,否则结果为False。 False >>> a > b or a < b # 如果有两个操作数至少有一个为True, 那么条件变为True,否则为False。 True >>> not a > b # 反转操作的状态,操作数为True,则结果为False,反之则为True False 成员运算符: not in 、in (判断某个单词里是不是有某个字母) >>> "h" in "hello" # 这里的意思是 “h” 在“Hello” 中,判断后结果为True True >>> "h" not in "hello" # 这里的意思是 “h” 不在“Hello” 中,判断后结果为False False 身份运算符: is、is not(讲数据类型时讲解,一般用来判断变量的数据类型) >>> a = 123456 >>> b = a >>> b is a #判断 a 和 b 是不是同一个 123456 True >>> c = 123456 >>> c is a #判断 c 和 a 是不是同一个 123456 False >>> c is not a #判断 c 和 a 是不是不是同一个 123456 True
while循环
while 条件: print("any")
else: ###当while语句正常结束时执行,如被break,则不执行
......
[root@node206 code]# cat test.py num = 1 while num<=10: print (num) num+=1 if num == 5: break ###break 终止循环 [root@node206 code]# python3 test.py 1 2 3 4
[root@node206 code]# cat test.py
num=0
while num<10:
num+=1
if num==3:
continue
print (num)
[root@node206 code]# python3 test.py
1
2
4
5
6
7
8
9
10
#####continue跳过本次循环
[root@node206 code]# cat test.py num = 1 while num<=10: if num%2==0: print(num) num+=1 [root@node206 code]# python3 test.py 2 4 6 8 10 猜年龄 [root@node206 code]# cat test.py age=50 flag=True while flag: user_input_age = int(input("Age is :")) if user_input_age == age: print("Yes") flag =False elif user_input_age > age: print("Is bigger") else: print("Is smaller") print("End") [root@node206 code]# python3 test.py Age is :60 Is bigger Age is :40 Is smaller Age is :50 Yes End
[root@node206 code]# cat test.py exit_flag=False for i in range(10): if i<5: continue print(i) for j in range(10): print("layer",j) if j==6: exit_flag=True break if exit_flag: break [root@node206 code]# python3 test.py 5 layer 0 layer 1 layer 2 layer 3 layer 4 layer 5 layer 6
打印阵列
[root@node206 code]# cat test.py height=int(input("height:")) width=int(input("width:")) num_height=1 while num_height<=height: num_width=1 while num_width<=width: print ("#",end="") num_width+=1 print("hello") num_height+=1 [root@node206 code]# python3 test.py height:3 width:4 ####hello ####hello ####hello
[root@node206 code]# cat while.py counter=0 while True: if counter>100000: break print ("ok") counter+=1 print (counter) [root@node206 code]# cat while.py _user="gtms" _passwd="rootabcd" counter=0 while counter<3: username=input("Username:") password=input("Password:") if username==_user and password==_passwd: print ("Welcome %s login"%_user) break else: print("Invalid username or password") counter += 1 else: print ("too many tries") [root@node206 code]# cat while.py _user="gtms" _passwd="rootabcd" counter=0 while counter<3: username=input("Username:") password=input("Password:") if username==_user and password==_passwd: print ("Welcome %s login"%_user) break else: print("Invalid username or password") counter += 1 if counter==3: loginagain=input("login again?[y/n]") if loginagain=="y": counter=0 else: print ("too many tries")
[root@node206 code]# cat test.py height=int(input("height:")) width=int(input("width:")) num_height=1 while num_height<=height: print(num_height,end="") num_width=2 while num_width<=width: print (num_width,end="") num_width+=1 num_height+=1 print("") [root@node206 code]# python3 test.py height:3 width:3 123 223 323
[root@node206 code]# cat test.py line=int(input("line:")) while line>0: tmp=line while tmp>0: print("*",end="") tmp-=1 print() line-=1 [root@node206 code]# python3 test.py line:5 ***** **** *** ** *
[root@node206 code]# cat test.py line=int(input("line:")) num=1 while num<=line: tmp=num while tmp>0: print("*",end="") tmp-=1 print() num+=1 [root@node206 code]# python3 test.py line:5 * ** *** **** *****
[root@node206 code]# cat test.py line=int(input("line:")) num=1 while num<=line: tmp=1 while tmp<=num: print(tmp,"*",num,"=",num*tmp,end="\t")
#=====〉print(str(tmp)+"*"+str(num)+"="+str(num*tmp),end="\t") tmp+=1 print() num+=1 [root@node206 code]# python3 test.py line:9 1 * 1 = 1 1 * 2 = 2 2 * 2 = 4 1 * 3 = 3 2 * 3 = 6 3 * 3 = 9 1 * 4 = 4 2 * 4 = 8 3 * 4 = 12 4 * 4 = 16 1 * 5 = 5 2 * 5 = 10 3 * 5 = 15 4 * 5 = 20 5 * 5 = 25 1 * 6 = 6 2 * 6 = 12 3 * 6 = 18 4 * 6 = 24 5 * 6 = 30 6 * 6 = 36 1 * 7 = 7 2 * 7 = 14 3 * 7 = 21 4 * 7 = 28 5 * 7 = 35 6 * 7 = 42 7 * 7 = 49 1 * 8 = 8 2 * 8 = 16 3 * 8 = 24 4 * 8 = 32 5 * 8 = 40 6 * 8 = 48 7 * 8 = 56 8 * 8 = 64 1 * 9 = 9 2 * 9 = 18 3 * 9 = 27 4 * 9 = 36 5 * 9 = 45 6 * 9 = 54 7 * 9 = 63 8 * 9 = 72 9 * 9 = 81
格式化输出 %s 占位符string %d 整数 %f 浮点数 [root@node206 code]# cat test.py name=input("Name:") age=input("Age:") job=input("Job:") salary=input("Salary:") if salary.isdigit(): #判断是否长的像数字 salary=int(salary) else: # print("must input digit") # salary=input("Salary:") exit("error:must input digit") msg=''' ------info of %s----------- Name: %s Age: %s Job: %s Salary: %s retired in %s years. ------end----------------- '''%(name,name,age,job,salary,65-int(age)) print (msg) [root@node206 code]# cat test.py name=input("Name:") age=input("Age:") job=input("Job:") salary=input("Salary:") msg=''' ------info of %s----------- Name: %s Age: %s Job: %s Salary: %d retired in %s years. ------end----------------- '''%(name,name,age,job,salary,65-int(age)) print (msg) [root@node206 code]# python3 test.py Name:gtms Age:36 Job:teacher Salary:4r Traceback (most recent call last): File "test.py", line 14, in <module> '''%(name,name,age,job,salary,65-int(age)) TypeError: %d format: a number is required, not str
for循环
[root@node206 code]# cat test1.py for i in range(10): if i%2==0: print (i) for i in range(1,4): print ("loop:",i) for i in range(1,10,2): print (i) [root@node206 code]# python3 test1.py 0 2 4 6 8 loop: 1 loop: 2 loop: 3 1 3 5 7 9 [root@node206 code]# cat test1.py for i in range(10): if i<2 or i>8: print (i) [root@node206 code]# python3 test1.py 0 1 9 _user="gtms" _passwd="rootabcd" passed_auth= False for i in range(3): username=input("Username:") password=input("Password:") if username==_user and password==_passwd: print ("Welcome %s login"%_user) passed_auth= True break else: print("Invalid username or password") if passed_auth==False: print("too many true") ==>优化 _user="gtms" _passwd="rootabcd" for i in range(3): username=input("Username:") password=input("Password:") if username==_user and password==_passwd: print ("Welcome %s login"%_user) break else: print("Invalid username or password") else: #只要for是正常执行完成,不被break打断过,则执行 print("too many true")
[root@node206 code]# cat gouwuche.py product_list=[ ('mac',9000), ('kindle',1000), ('tesla',900000), ('mysqlbook',100), ('bike',2000) ] saving=input('please input your money:') shopping_car=[] if saving.isdigit(): saving=int(saving) # for i in product_list: # print(product_list.index(i),i) # for i in enumerate(product_list,1): # print(i) while True: for i,j in enumerate(product_list,1): print(i,">>>",j) choice=input("your choice[q,quit]") if choice.isdigit(): choice=int(choice) if choice>0 and choice<=len(product_list): p_item=product_list[choice-1] if p_item[1]<saving: saving-=p_item[1] shopping_car.append(p_item) else: print ("not enough money,%s left" %saving) print(p_item) else: print ("not exist") elif choice=="q": print ("---------you have buyed-----------") for i in shopping_car: print(i) print ("%syuan left" %saving) break else: print("invalid input")