#!/usr/bin/env python# -*- coding: utf-8 -*-"""__title__ = ‘‘__author__ = ‘wlc‘__mtime__ = ‘2017/3/13‘"""print("hello world!")import keywordprint(keyword.kwlist)word = "嗨喽"print (word)#input("/n/n hello")import sysfor i in sys.argv: print(i)print (‘/n python 路径‘, sys.path)counter = 100miles = 1000.0name = "runoob"print (counter)print (miles)print (name) a,b,c = 1,2,"same"print (a,b,c) d = Trueprint(d+1)#String(字符串)str = "Hello"print(str)print (str[0:-1])# 输出第一个到倒数第二个的所有字符print (str[0])# 输出第一个字符print (str[2:5])#输出第三个到第五个字符print (str[2:])#输出从第三个开始的所有字符print (str * 2)#输出两次print (str + "world")#拼接字符串print (str[-1],str[-5])# 输出倒数第一个和倒数第二个字符 #List 列表list = [‘abcd‘,786,2.23,‘runoob‘,70.2]tinylist = [123,‘runoob‘] print(list)print (list[0])print (list[1:3])#第二个到第三个print (list +tinylist) #Tuple 元组tuple = (‘abcd‘,786,2.23,‘runoob‘,70.2)print (tuple) #Set 集合student = {‘Tom‘,‘Jim‘,‘Mark‘,‘Tom‘,‘Jack‘,‘Rose‘}print (student)if(‘Rose‘in student): print (‘Rose 在集合中‘)else : print (‘Rose不在集合中‘) #Set集合运算a = set(‘absderthgj‘)b = set(‘asdgaghjjlsd‘) print (a-b) #a,b 差集print (a | b) #并集print (a & b) #交集print (a ^ b) #a,b 不同时存在的元素 #Dictionary字典dict = {}dict[‘one‘] = "1-数据结构"dict[2] = "2-计算机网络"print (dict[‘one‘])print (dict[2])print (dict)print (dict.keys())print (dict.values()) ‘‘‘这是多行注释‘‘‘"""多行注释""" print (word)print ("更新字符串:",word[:1] +‘ WLC!‘)print ("我叫 %s 今年 %d 岁" % (‘WLC‘,23)) errHTML = ‘‘‘<HTML><HEAD><TITLE>Friends CGI Demo</TITLE></HEAD><BODY><H3>ERROR</H3><B>%s</B><P><FORM><INPUT TYPE=button VALUE=BackONCLICK="window.history.back()"></FORM></BODY></HTML>‘‘‘print (errHTML)"""#迭代器list = [1,3,4,5]it = iter(list)while True: try: print (next(it)) except StopIteration: sys.exit()#生成器(generator) 生成器是一个返回迭代器的函数,只能用于迭代操作使用yield的函数 """ #函数def area(width, height): return width * heightwidth = 1height = 2 print ("面积:%d" % area(width, height)) # fun(a) 内部修改a:整数,字符串,元组(不可变类型) 只是修改另一个复制的对象 不会影响a本身 类似于C++ 值传递# fun(la) 内部修改la:列表,字典(可变类型) la 真正传递过去 函数内部修改后 外部la 也会发生变化 类似于 C++引用传递 def changeInt(a): a = 10b = 2changeInt(b)print (b) #b未发生变化 def changeMe(myList): "修改传入的列表" myList.append([1,2,3,4]) print(myList) returnmyList = [4,5,6,7]changeMe(myList)print("函数外值:", myList) #list 发生变化 #参数def printinfo(name, age = 20): print ("姓名:",name) print ("年龄:",age) returnprintinfo(age =10, name="Tom")#参数不需要使用指定顺序 ,python解释器可以使用参数名匹配参数值printinfo(name="Kitty")#如果不传参数则使用默认的参数 def functionname(arg1, *vartuple): print ("输出:") print (arg1) for var in vartuple: print (var) returnfunctionname(10)functionname(10,20,30,45,46)# 加了*的变量名会存放所有未命名的变量参数。如果函数调用时没有指定参数就是一个空元组 #匿名函数"""lambda 创建匿名函数lambda 只是一个表达式 """sum = lambda arg1, arg2: arg1 + arg2print ("sum:",sum (10, 20)) #python3 变量作用域"""local 局部作用域enclosing 闭包函数外的函数中global 全局作用域built-in 内建作用域规则查找 : l->e->g->b"""x = int(2.8) #内建作用域g_count = 0 #全局作用域 def outer(): o_count = 1 #闭包函数外的函数中 def inner(): i_count = 2 #局部作用域 return return #全局变量 局部变量total = 0 #全局变量def sum(arg1, arg2): total = arg1 + arg2 #局部变量 print("函数内部是局部变量:",total) return totalsum(10,20)print ("函数外是全局变量:",total) #global nonlocal 关键字num = 1def fun1():#内部作用域修改外部作用域 若不使用global 则全局变量只是可读的 不可以修改 global num print (num) num = 12345 print (num)fun1() def outer1():#修改嵌套作用域 (enclosing) num = 10 def inner1(): nonlocal num num = 100 print ("\n",num) inner1() print (num)outer1() #数据结构a = [2,4,5.6,7,8,9,10.3]a.append(33)print (a)b = a.copy()print (b)print (a.count(1)) #将列表当做堆栈使用stack = [1,23,4,6,88]stack.pop()print(stack) #队列from collections import dequequeue = deque(["Tom","John","Michael"])queue.append("Terry")queue.popleft()print(queue) #列表推导式vec = [2,4,6]vec2 = [3,5,7]print ([3*x for x in vec])print ([[x,x**2]for x in vec])print ([3*x for x in vec if x >3])print ([x*y for x in vec for y in vec2])print ([vec[i]*vec2[i]for i in range(len(vec2))]) #嵌套列表解析 matrix = [[1,2,3,9],[4,5,6,8],[7,8,9,5]]# 3*4 变为4*3print ([[row[i]for row in matrix]for i in range(4)]) # del语句del matrix[0]print (matrix) #元组和序列t = 123,456,‘tom‘ #元组在输出时候是有括号的print(t[0])print (t) #集合#字典for k,v in dict.items(): print(k,v)dict2 = [‘name‘,‘question‘,‘color‘]dict3 = [‘blue‘,‘red‘,‘write‘]for aa,bb in zip(dict2, dict3): print (‘{0}.{1}‘.format(aa,bb))for i in reversed(range(1,10,2)):#逆序遍历 print (i) #模块:包含你定义的函数和变量 每个模块都有一个__name__属性,当其值是‘__main__‘时,表明该模块自身在运行,否则是被引入。import sysprint (dir(sys)) #找到模块定义的所有名称 #输入与输出for x in range (1,8):# rjust 方法可以让字符串靠右对其并且左边添加空格 print (repr(x).rjust(2),repr(x*x).rjust(3), end=‘ ‘) print (repr(x**3).rjust(4))for x in range (1,8): print (‘{0:2d}{1:3d}{2:4d}‘.format(x,x**2,x**3))#str = input("请输入:")#print (str) #读和写文件#f = open("D:/FavoriteVideo/readme.txt","r")#f.write("python is good! \n" + str)#str = f.read()#print(str)#str = f.readlines()#print(str) #pickle 模块import pickle"""selffile = [1,2,3]selffile.append(selffile)output = open(‘D:/FavoriteVideo/data.pkl‘,‘wb‘)pickle.dump(dict,output)pickle.dump(selffile,output,-1)output.close()"""import pprintpkl_files = open(‘D:/FavoriteVideo/data.pkl‘,‘rb‘)data = pickle.load(pkl_files)pprint.pprint(data)data2 = pickle.load(pkl_files)pprint.pprint(data2)pkl_files.close()
时间: 2024-10-19 17:34:45