Hello Python3
print("Hello Python!") #print("Hello, Python!"); '''a=1 b=2 c=a+b print(c) ''' #列表:存储多个元素的东西,列表里面的元素是可以重新赋值的 a=[1,"a"] a[0]=2 #元组:存储多个元素的东西,元组里面的元素不可用重新赋值 b=(1,"b") #字典 #{key1:value1, key2:value} #集合 #去重 #if语句 a=10 b=1 if(a > 9): print(a) if(b < 9): print(b) age=18 if(age <= 10): print("儿童") elif(age > 10 and age <= 20): print("青少年") elif(age > 20): print("青年") else: print("小伙子") #while语句 a=0 while(a<10): print("hello") a += 1 #for语句:遍历列表 a=["aa", "bb", "cc", "dd"] for i in a: print(i) #for语句:常规循环 for i in range(0, 10): print(i) for i in range(0, 10): print("AAA") #中断退出:continue,break for i in a: if(i=="cc"): break print(i) for i in a: if(i=="cc"): continue print(i) #乘法口诀 #end=""表示不换行输出 for i in range(1, 10): for j in range(1, i+1): print(str(i) + "*" + str(j) + "=" + str(i*j), end=" ") print() print("-----------------------") for i in range(9, 0, -1): for j in range(1, i+1): print(str(i) + "*" + str(j) + "=" + str(i*j), end=" ") print() ''' #作用域 i=10 def func(): j=20 print(j) print(j) ''' #函数 #函数定义格式: #def 函数名(参数): # 函数体 def abc(): print("abcdef") #调用函数:函数名(参数) abc() def func2(a, b): if(a > b): print("a>b") else: print("a<=b") func2(1,2) func2(5,4) #模块导入 import cgi cgi.closelog() from cgi import closelog #文件操作 #打开 open(文件路径, 操作形式) ''' w:写 r:读 b:二进制 a:追加 ''' file = open("D:/python/1.txt", "r") data=file.read() print(data) data=file.readline() print(data) file.close() #文件写入 data2="一起学python" file2=open("D:/python/2.txt", "w") file2.write(data2) file2.close() data2="Java" file2=open("D:/python/2.txt", "a+") file2.write(data2) file2.close() #异常处理 try: a = 1 / 0 except Exception as ex: print(ex) #类 class User: def __init__(self): print("无参构造函数") a=User() class Person: def __init__(self, name, age): print("带参数的构造函数,name=" + name + ", age=" + age) c1=Person("zhangsan", str(20)) c2=Person("lisi", str(22)) class Rabbit: def __init__(self, name, color): self.name = name self.color = color def func1(self): print("aaa"); def func2(self, age): print("这个兔子已经" + str(age) + "岁了") def toString(self): print("Rabbit [name=" + self.name + ", color=" + self.color + "]") r1 = Rabbit("流氓兔", "白色") r1.func1() r1.func2(3) r1.toString() #继承 class Father(): def write(self): print("写作") class Son(Father): pass class Mother(): def draw(self): print("画画") def makeDinner(self): print("做饭") class Daughter(Father, Mother): def draw(self): print("素描") son = Son() son.write() daughter = Daughter() daughter.write() daughter.draw() daughter.makeDinner() print("Hello\n" * 3) #str是关键字是函数名不能随便用 tmp = input("请输入一个数字:") print(tmp) #递归 def factorial(n): if(n == 1): return 1 else: return n * factorial(n-1) number = int(input("请输入一个正整数:")) result = factorial(number) print("%d的阶乘是%d"%(number, result)) def fab(n): if(n == 1 or n == 2): return 1 else: return fab(n-1) + fab(n-2) number = int(input("请输入一个正整数:")) result = fab(number) print("总共" + str(result) + "对兔子")
数据类型以及传参
# 数据类型 num = 123 print(type(num)) f = 2.0 f = 5.0 / 2 print(f) str1 = 'hello world' print(str1) str2 = "hello world" print(str2) str3 = "hello \"world\"" str4 = "hello 'world'" print(str3) print(str4) str5 = "Jack: \nI love you" print(str5) mail = """ Rose: I'am Jack goodbye """ print(mail) str6 = "abcdef" print(str6[0]) print(str6[1]) print(str6[0] + str6[1]) print(str6[1:4]) print(str6[4:]) print(str6[:4]) print(str6[2:]) print(str6[::2]) print(str6[-1]) print(str6[-4:-1]) str7 = "1234" print(id(str7)) str7 = "1234" print(id(str7)) # 元组 t = ("Jack", 19, "male") print(t) print(t[0]) print(type(t)) t2 = (3,) print(type(t2)) print(len(t2)) print(len(str6)) a,b,c=(1,2,3) print(a) print(b) print(c) a,b,c=t print(a) print(b) print(c) # 列表 list1 = ["jack", 21, True, [1,2,3]] print(list1[0]) print(type(list1)) print(list1[3]) print(len(list1)) list1[0]="rose" list1[1]="jerry" print(list1) list1.append(3) print(list1) list1.remove(3) del(list1[2]) print(list1) list2 = [1,2,3] list2.append(4) # 查看帮助 help(list) help(list.remove) help(len) # 字典 dict1 = {"name":"jack", "age":25, "gender":"male"} print(dict1["name"]) print(dict1.keys()) print(dict1.values()) dict1["phone"] = "13712345678" dict1["phone"] = "15923423455" print(dict1) del dict1["phone"] print(dict1) print(dict1.pop("age")) # 条件语句 if 1 < 2: print(1234) if(2 > 1): print("hhh") if(True): print("ok") if(1+1): print("yes") # for循环 print(range(1,10)) print(range(1, 10, 2)) print(range(5)) arr = ['a', 'b', 'c', 'd'] for i in arr: print(i) for i in range(len(arr)): print(arr[i]) num = 0 for i in range(101): num += i print(num) for i in range(3): print(i) else: print("finish") # 遍历字典 d = {1:111, 2:222, 3:333} for x in d: print(d[x]) for k,v in d.items(): print(k) print(v) d2 = {"name":"zhangsan", "age":20} for k,v in d2.items(): print(k) print(v) # 函数 def func(): print("123") func() def func2(x, y): print(x) print(y) func2(3,4) # 参数的默认值 def func3(x=5,y=6): print("x=" + str(x) + ", y=" + str(y)) func3() func3(7,8) def func4(x, y=9): print("x=" + str(x) + ", y=" + str(y)) func4(10) func4(11, 12) def func5(): x = input("Please Enter A Number: ") print(x) func5() def func6(): global a a = "good" func6() print(a) # 传参:元组 # 传元组 def f(x,y): print("x=%s, y=%s" % (x,y)) f(1,2) f(*(3,4)) t = ("Tom", "Jerry") f(*t) def f1(x, y): print("x=%s, y=%s" % (x, y)) t = (20, "Jack") f1(*t) # 传字典 def f2(name, code, age): print("name=%s, code=%s, age=%s" % (name, code, age)) d = {"name": "zhangsan", "code": "10001", "age": 22} f2(**d) d["age"] = 28 f2(**d) f2(d["name"], d["code"], d["age"]) # 参数冗余 # 多余的实参 def f3(x, *args): print(x) print(args) f3(1) f3(1,2) f3(1,2,3,4) def f4(x, *args, **kwargs): print(x) print(args) print(kwargs) f4(1) f4(1, 2) f4(1, 2, 3) f4(1, y=3, z=4) f4(1, **d) f4(1, 2, 3, 4, y=6, z=7, xy=8) # lambda表达式 f6 = lambda x,y:x*y print(f6(3, 4))
内置函数
# Python内置函数 print(abs(2)) print(abs(-2)) r = range(11) print(max(r)) print(min(r)) print(max([3,2,1,9])) print(len(r)) print(divmod(5,3)) print(pow(2,10)) print(round(2.5)) print(type(r)) a = "1234" print(int(a)) b = 99 print(str(b)) print(hex(b)) print(list([1,2,3,4])) # 字符串函数 # str.capitalize() 首字母大写 # str.replace() 字符替换 # str.split() 分割 help(str.capitalize) help(str.replace) help(str.split) s = "hello" print(s.capitalize()) y = "123123123123" print(y.replace("12", "AB")) print(y.replace("12", "AB", 1)) print(y.replace("12", "AB", 2)) ip = "192.168.12.93" print(ip.split(".")) print(ip.split(".", 1)) print(ip.split(".", 2)) # 序列处理函数 help(filter) help(zip) help(map) from functools import reduce help(reduce) def f1(x): if(x > 0): return True return False r = [1,2,-1,-2,0,3] ss = filter(f1, r) print(ss) print(list(filter(lambda x:x%2==0, range(10)))) result = filter(lambda x:x*2, [1, 2, 3, 4, 5]) print(result) print(list(result)) print(list(filter(lambda x: x%2 == 0, range(8)))) # 这里的map函数和reduce函数就相当于MapReduce中的Map阶段和Reduce阶段 # Map阶段计算,Reduce阶段合并结果 foo = [2, 18, 9, 22, 17, 24, 8, 12, 27] print(list(filter(lambda x:x % 3 == 0, foo))) print(map(lambda x:x*2+10, foo)) print(list(map(lambda x:x*2+10, foo))) print(reduce(lambda x, y: x+y, [1, 2, 3, 4, 5])) print(reduce(lambda x, y: x*y, range(1, 6))) print(reduce(lambda x,y:x+y, foo)) t1 = ["zhangsan", "lisi", "wangwu", "zhaoliu"] t2 = ["北京", "上海", "广州", "深圳"] t3 = [20, 21, 22, 23] res = zip(t1, t2, t3) print(list(res)) ''' 包 Python的模块可以按目录组织为包 创建一个包的步骤是: 1、建立一个名字为包名字的文件夹 2、在该文件夹下创建一个__init__.py文件 3、根据需要在该文件夹下存放脚本文件、已编译扩展及子包 4、import pack.m1, pack.m2, pack.m3 模块 模块是Pyhon组织代码的基本方式 Pyhon的脚本都是用扩展名为py的文本文件保存的,一个脚本可以单独运行, 也可以导入另一个脚本中运行。当脚本被导入运行时,我们将其称为模块(module) 模块名与脚本的文件名相同(例如,我们编写了一个名为items.py的脚本,则可以在另一个脚本中用import items语句来导入它) '''
正则表达式
# 正则表达式 # 参考菜鸟教程 http://www.runoob.com/python3/python3-reg-expressions.html import re print(re.match('www', 'www.baidu.com')) print(re.match('www', 'www.baidu.com').span(0)) print(re.match('com', 'www.baidu.com')) line = "Cats are smarter than dogs" matchObj = re.match(r'(.*) are (.*?) .*', line, re.M|re.I) if matchObj: print(matchObj.group()) print(matchObj.group(1)) print(matchObj.group(2)) else: print("No match!!!") print(re.search('www', 'www.baidu.com').span()) print(re.search('com', 'www.baidu.com').span()) # re.match与re.search的区别 # re.match只匹配字符串的开始,如果字符串开始不符合正则表达式,则匹配失败,函数返回None; # 而re.search匹配整个字符串,直到找到一个匹配。 line = "Cats are smarter than dogs" # 简单地来说,re.match看的是字符串是不是以指定的正则表达式开头的 matchObj = re.match(r'dogs', line, re.M|re.I) if matchObj: print("match --> matchObj.group(): ", matchObj.group()) else: print("No match!!!") matchObj = re.search(r'dogs', line, re.M|re.I) if matchObj: print("search --> matchObj.group(): ", matchObj.group()) else: print("No match!!!") # 检索和替换 # re.sub用于替换字符串中的匹配项 # # 语法:re.sub(pattern, repl, string, count=0) # 参数: # pattern : 正则中的模式字符串。 # repl : 替换的字符串,也可为一个函数。 # string : 要被查找替换的原始字符串。 # count : 模式匹配后替换的最大次数,默认 0 表示替换所有的匹配。 phone = "2004-959-559 # 这是一个电话号码" num = re.sub(r'#.*$', "", phone) print("电话号码:", num) num = re.sub(r'\D', "", phone) print("电话号码:", num) # compile函数 # compile 函数用于编译正则表达式,生成一个正则表达式( Pattern )对象,供 match() 和 search() 这两个函数使用。 # 语法:re.compile(pattern[, flags]) pattern = re.compile(r'\d+') m = pattern.match('one1two2three3four4') print(m) m = pattern.match('one1two2three3four4', 3, 10) print(m) print(m.group()) print(m.start()) print(m.end()) print(m.span()) # group([group1, …]) 方法用于获得一个或多个分组匹配的字符串,当要获得整个匹配的子串时,可直接使用 group() 或 group(0); # start([group]) 方法用于获取分组匹配的子串在整个字符串中的起始位置(子串第一个字符的索引),参数默认值为 0; # end([group]) 方法用于获取分组匹配的子串在整个字符串中的结束位置(子串最后一个字符的索引+1),参数默认值为 0; # span([group]) 方法返回 (start(group), end(group))。 # findall # 在字符串中找到正则表达式所匹配的所有子串,并返回一个列表,如果没有找到匹配的,则返回空列表。 # # 注意: match 和 search 是匹配一次 findall 匹配所有。 # 语法:findall(string[, pos[, endpos]]) # 参数: # string 待匹配的字符串 # pos 可选参数,指定字符串的起始位置,默认为0 # endpos 可选参数,指定字符串的结束位置,默认为字符串的长度 pattern = re.compile(r'\d+') result1 = pattern.findall('runoob 123 google 456') result2 = pattern.findall('run88oob123google456', 0, 10) print(result1) print(result2) # re.finditer # 和 findall 类似,在字符串中找到正则表达式所匹配的所有子串,并把它们作为一个迭代器返回。 it = re.finditer(r"\d+", "12a23bce34fj666") for match in it: print(match.group()) # re.split # split 方法按照能够匹配的子串将字符串分割后返回列表 # 语法:re.split(pattern, string[, maxsplit=0, flags=0]) print(re.split('\W+', 'abc, runoob, wahaha, 1342')) print(re.split('(\W+)', 'abc, runoob, wahaha, 1342')) print(re.split('\W+', 'abc, runoob, wahaha, 1342', 1)) print(re.split('a+', 'hello world'))# 对于一个找不到匹配的字符串而言,split 不会对其作出分割
文件操作
# 文件读写 f = open("D:/python/a.txt","r") print(f.readline()) txt = f.read() print(txt) f.close() ## f.read() f = open("D:/python/a.txt","r") for line in f: print(line) f.close() f = open("D:/python/b.txt","w+") f.write("I am Mr.Cheng") f.write("Very Good!") print(f.read()) f.flush() f.seek(0) print(f.read()) f.close() f = open("D:/python/b.txt","a+") f.write("\nhot") f.seek(0) print(f.read()) f.close()
异常处理
# finally try: ff = open("D:/python/b.txt","a+") except Exception: print(1) finally: ff.close() print(2) try: f = open("abc.txt") f.close() except (OSError, RuntimeError, TypeError, NameError): pass try: f = open("abc.txt") f.close() except OSError as err: print("OSError") except ValueError: print("ValueError") except NameError: print("NameError") except: print("Unexpected Error") # raise 抛出异常 try: x = int(input("Please enter a number: ")) if(x == 123): raise NameError("You are kidding!") except NameError: print("name error") except ValueError: print("value error") except TypeError: print("type error") finally: print("Goodbye")
类和对象
# 类和对象 class MyClass: i = 123 def m(self): return 'hello' x = MyClass() print(x.i) print(x.m()) # __init__()是构造方法 class Person: name = "" age = 0 def __init__(self): print("无参构造方法被调用") def __init__(self, name, age): print("带参数的构造法被调用") self.name = name self.age = age def toString(self): print("Person [name={0}, age={1}]".format(self.name, self.age)) person = Person("zhangsan", 25) person.toString() print(id(person)) # self 代表类的实例,self 在定义类的方法时是必须有的,虽然在调用时不必传入相应的参数 # self相当于Java中的this # 类的方法必须有一个额外的第一个参数,按照惯例它的名称是 self class Employee: empCount = 0 def __init__(self, name, salary): self.name = name self.salary = salary Employee.empCount += 1 def displayCount(self): print("Total Employee %d" % Employee.empCount) def toString(self): print("wahaha") employee1 = Employee("zhangsan", 27) employee2 = Employee("lisi", 28) employee3 = Employee("wangwu", 29) print(Employee.empCount) print(employee1.displayCount()) print(employee2.name) print(employee3.salary) print(Employee.__name__) print(Employee.__module__) # 继承 class Leader(Employee): def __init__(self): print("调用子类的构造方法") leader = Leader() leader.toString() class Father: def sing(self): print("我会唱歌") def write(self): print("我擅长写粉笔字") class Mother: def dance(self): print("我会跳舞") class Son(Father, Mother): def draw(self): print("我会画画") def write(self): print("我擅长写毛笔字") son = Son() son.sing() son.dance() son.draw() son.write() # 两个下划线开头,声明该属性为私有,不能在类的外部被使用或直接访问。在类内部的方法中使用时 self.__private_attrs # 两个下划线开头,声明该方法为私有方法,不能在类的外部调用。在类的内部调用 self.__private_methods class Daughter: name = "" # public属性 _height = 0 # protected属性 __age = 0 # private属性 def __init__(self, name, height, age): self.name = name self._height = height self.__age = age def getName(self): # public return self.name def __getAge(self): # private return self.__age def getAge(self): return self.__age daughter = Daughter("Alice", 170, 24) print(daughter.name) print(daughter._height) #print(daughter.__age) #print(daughter.__getAge()) print(daughter.getAge())
MySQL操作
import pymysql ''' # 建立连接 conn = pymysql.connect("localhost", "root", "123456", "mytest") # 获取游标 cursor = conn.cursor() # SQL语句 #sql = "insert into user_info(name, family, sword) values('蓝忘机', '姑苏蓝氏', '避尘')" sql = "insert into user_info(name, family, sword) values('%s', '%s', '%s')" % ('魏无羡', '云梦江氏', '随便') try: # 执行SQL cursor.execute(sql) # 提交 conn.commit() except: # 回滚 conn.rollback() finally: # 关闭连接 conn.close() # 批量插入 conn = pymysql.connect("localhost", "root", "123456", "mytest") cursor = conn.cursor() sqlTemplate = "insert into user_info(name, family, sword) values('%s', '%s', '%s')" dataList = [('江澄', '云梦江氏', '三毒'), ('蓝曦臣', '姑苏蓝氏', '朔月'), ('金子轩', '兰陵金氏', '岁华')] try: # 方式一:使用execute for data in dataList: sql = sqlTemplate % data cursor.execute(sql) # 方式二:使用executemany insertTemplate = "insert into user_info(name, family, sword) values(%s, %s, %s)" dataArray = [('江澄', '云梦江氏', '三毒'), ('蓝曦臣', '姑苏蓝氏', '朔月'), ('金子轩', '兰陵金氏', '岁华')] cursor.executemany(insertTemplate, dataArray) conn.commit() except Exception as ex: print(ex) conn.rollback() finally: conn.close() ''' # 查询 # Python查询Mysql使用 fetchone() 方法获取单条数据, 使用fetchall() 方法获取多条数据。 # fetchone(): 该方法获取下一个查询结果集。结果集是一个对象 # fetchall(): 接收全部的返回结果行. conn = pymysql.connect("localhost", "root", "123456", "mytest") cursor = conn.cursor() # 隐式开启事务 sql = "select * from user_info" try: cursor.execute(sql) # 返回受影响的行数 records = cursor.fetchall() for row in records: print(row) for row in records: # 数组的元素是元组 print("name=%s, family=%-3s, sword=%4s" % (row[0], row[1], row[2])) except: print("Error: unable to fetch data") finally: conn.close()
Socket编程
import socket import sys # 创建socket对象 serverSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # 绑定端口 # #host = socket.gethostname() host = "localhost" port = 9999 serverSocket.bind((host, port)) # 设置最大连接数 serverSocket.listen(5) # 监听客户端连接 while True: print(1234) clientSocket, addr = serverSocket.accept() print("客户端连接: %s" % str(addr)) msg = "Hello World" clientSocket.send(msg.encode("utf-8")) clientSocket.close()
import socket import sys clientSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) print(4455) clientSocket.connect(("localhost", 9999)) msg = clientSocket.recv(1024) print(msg.decode("utf-8"))
线程
import threading import time ''' 相当于 class MyThread extends Thread { public Integer threadId; public String threadName; public MyThread(Integer threadId, String threadName) { this.threadId = threadId; this.threadName = threadName; } @Override public void run() { System.out.print(this.threadName + " : " + new Date()); } } Thread thread1 = new MyThread(); Thread thread2 = new MyThread(); thread1.start(); thread2.start(); ''' class MyThread(threading.Thread): def __init__(self, threadId, threadName): threading.Thread.__init__(self) self.threadId = threadId self.threadName = threadName def run(self): print("启动线程:" + self.name) self.do_something() def do_something(self): print("%s: %s" % (self.threadName, time.ctime(time.time()))) thread1 = MyThread(1, "Thread-1") thread2 = MyThread(2, "Thread-2") thread1.start() thread2.start() print("****************************************") # 相当于synchronized代码块 threadLock = threading.Lock() class Ticket: __total = 100 def decr(self): threadLock.acquire() time.sleep(1) if self.__total > 0: self.__total = self.__total - 1 print("成功售出一张票,剩余%s张" % self.__total) else: print("今日已售罄") threadLock.release() class Customer(threading.Thread): def __init__(self, ticket): threading.Thread.__init__(self) self.ticket = ticket def run(self): self.ticket.decr() ticketObj = Ticket() for i in range(150): consumer = Customer(ticketObj) consumer.start()
HTTP请求
import urllib.request import urllib.parse import requests resp = urllib.request.urlopen("http://www.baidu.com/") html = resp.read().decode("utf-8") print(html) # GET resp = urllib.request.urlopen("http://localhost:8080/sayHello?name=zhangsan") print(resp.status) print(resp.read().decode("UTF-8")) # POST data = urllib.parse.urlencode({"username": "lisi", "password":"123456"}) data = data.encode("UTF-8") resp = urllib.request.urlopen("http://localhost:8080/login", data) print(resp.read().decode("UTF-8")) # 带Header header = { "POSID": "1010101" } req = urllib.request.Request("http://localhost:8080/login", data, header) resp = urllib.request.urlopen(req) print(resp.read().decode("UTF-8")) # requests # GET response = requests.get("http://localhost:8080/sayHello", "name=zhangsan") print(response.status_code) print(response.headers) print(response.headers["Content-Type"]) print(response.encoding) print(response.text) # POST # 类似jQuery # response = requests.post("http://localhost:8080/login", {"username":"lisi","password":"123456"}) response = requests.post("http://localhost:8080/login", "username=lisi&password=123456") if response.status_code == 200: print(response.text) print(response.json()) # 带headers url = "http://localhost:8080/login" data = "username=lisi&password=123456" headers = {"id":"123", "name": "abc"} response = requests.post(url, data, headers=headers, timeout=3) if response.status_code == 200: print(response.text) print(response.json())
JSON
import json # Python中的json库提供的主要功能是在字典和JSON之间做转换 # json.dumps(): 转成JSON # json.loads(): JSON字符串转字典 data_list = [1, 2, 'a', 'b', True, [4, 5, 6]] json_str = json.dumps(data_list) print(json_str) data2 = {'name': 'zhangsan', 'age': 25} json_str2 = json.dumps(data2) print("原对象:", data2) print("JSON对象:", json_str2) data3 = '{"a":"b"}' json_str3 = json.loads(data3) print("原对象:", data3) print("字典对象:", json_str3) print()
日期时间
import time from datetime import date from datetime import datetime from datetime import timedelta import calendar # time print("当前时间戳:", time.time()) print("本地时间:", time.localtime(time.time())) print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())) # 日历 cal = calendar.month(2018, 8) print(cal) # date print(date.today()) startDate = date(2018, 6, 1) endDate = date(2018, 8, 5) print(startDate) print(endDate) diff = endDate - startDate print(diff.days) # print(diff.seconds) # datetime print(datetime.now()) dt = datetime(2018, 8, 5, 19, 22, 18) print(dt) # 加3天 print(dt + timedelta(3)) # 减5天 print(dt + timedelta(-5)) # 加1小时 print(dt + timedelta(hours=1)) # 减2小时 print(dt + timedelta(hours=-2)) # 加25分钟 print(dt + timedelta(minutes=25)) # 减10分钟 print(dt + timedelta(minutes=-10))
感想
解决问题的思路才是关键,编程语言只是语法不同而已。
习惯性以分号结尾;哈哈哈!!!
原文:https://www.cnblogs.com/cjsblog/p/9427157.html