最近涉及到python的东西比较多,抽一点时间把基础语法规整下。

1、面向对象

#coding=utf-8

def _class_test_01():

    s = squire(3,4)

    print("width %d lenth %d area is %d"
%(s.width, s.length, s.calc_area())) class squire: width = 0
length = 0 #构造函数
def __init__(self, w, l): self.width = w
self.length = l def calc_area(self):
return self.width * self.length

2、列表、字典、元组

#coding=utf-8

def _container_test_01():

    # 列表
l_temp = ['fredric','fed', 'other','base'] # 获取长度及切片
print("len: "
+ str(len(l_temp)) # 长度 3
+ " value 1:3 "
+ ''.join(l_temp[1:3])) # fredother # 遍历列表
for item in range(0, len(l_temp)):
print(l_temp[item]) # 出队列
print(l_temp.pop(1)) # 注意insert会替换原来的值
l_temp.insert(1, 'hi')
print(l_temp) # fredric hi other # 排序
l_temp.sort() # 根据字母排序
print(l_temp) def _container_test_02(): #元组
t_temp_01 = (1,2,3,4,5)
t_temp_02 = (6,7) # 元组的数据不允许修改,但可以拼接
t_temp_03 = t_temp_01 + t_temp_02 print("len: %d value[1]: %d max: %d min: %d"
%(len(t_temp_03), t_temp_03[1],
max(t_temp_03), min(t_temp_03))) def _container_test_03(): # 字典
d_temp = {"username":"fredric", "password":"fredricpwd", "note":"none"} print(d_temp["username"])
print(d_temp["password"])
print(d_temp["note"]) del d_temp["note"] # 遍历字典
for key in d_temp.keys():
print(key + " " + d_temp[key]) d_temp.clear() print("key len after clear: %d" %(len(d_temp.keys())))

3、文件操作

#coding=utf-8
import fileinput def _file_test_01(): config = {} #db.cfg 中数据如下:
# host = 192.168.0.1
# db = test
# username = root
# password = root
for line in fileinput.input('./config/db.cfg'): key = line.split("=")[0].strip()
value = line.split("=")[1].strip() config.update({key:value}) # 打印保存在字典里的key/value
for key in config.keys():
print(key + " " + config[key])

4、语句流程

#coding=utf-8

# 该全局变量可以被使用
status = False def _flow_test_01(): v_str_01 = "abcdefg"
count = 0
global status while (count < len(v_str_01)): if v_str_01[count] == 'd': #此时修改的是全局变量status,如果没有上面局部变量的定义,则为一局部变量
status = True break elif v_str_01[count] == 'f': status = True break else:
status = False; count += 1 if True == status: print("get value: " + v_str_01[count])

5、http POST JSON数据

#coding=utf-8

import http.client, urllib.parse
import json # POST请求测试,请求和返回都是JSON数据
def _http_test_01(): str = json.dumps({'username':'fredric'}) headers = {"Content-type": "application/json",
"Accept": "text/plain"} conn = http.client.HTTPConnection("127.0.0.1" ,3000) conn.request('POST', '/dopost', str, headers)
response = conn.getresponse()
data = response.read().decode('utf-8') # 打印返回的JSON数据
print(json.loads(data)["res"])
print(json.loads(data)["data"]) conn.close()

6、mysql数据库操作

#coding=utf-8

#采用pip install PyMysql安装
import pymysql
import sys def _mysql_test_01(): db = pymysql.connect("localhost","root", "root", "demo") cursor = db.cursor() insert_sql = "INSERT INTO myclass(id, \
name, sex, degree) \
VALUES ('%d', '%s', '%d', '%d')" % \
(3, 'fred', 20, 2000) try:
cursor.execute(insert_sql)
db.commit()
except:
# 此处捕获异常,诸如主键重复时打印:pymysql.err.integrityerror
print("Error: insert failed:", sys.exc_info()[0])
db.rollback() select_sql = "SELECT * FROM myclass" try: cursor.execute(select_sql) results = cursor.fetchall()
for row in results:
print ("id=%d,name=%s,sex=%d,degree=%d" %(row[0], row[1], row[2], row[3]))
except: print ("Error: select failed", sys.exc_info()[0]) db.close()

7、字符串

#coding=utf-8

def _string_test_01():

    v_temp = "test string value"

    # 首字母大写
print(v_temp.capitalize()[0]) # 部分字符串
print(v_temp[0:3]); # 循环遍历字符串
for item in range(0, len(v_temp)):
print(v_temp[item]) def _string_test_02(): v_str_01 = "start"
v_str_02 = "end" v_str_list = [v_str_01, " ", v_str_02] # 字符串拼接
res = "".join(v_str_list)
print(res) # 字符串替换
print(res.replace('start', 'hello start')) def _string_test_03(): v_str_03 = "" v_int_01 = 0; # 字符串转整数,后面的8 代表8进制的整数
v_int_01 = int(v_str_03, 8) print(v_int_01 == 14)

8、线程

#coding=utf-8
import _thread
import threading
import time lock = threading.Lock() def _thread_test_01(): try:
_thread.start_new_thread( _do_thread, ("thread_01",1,))
_thread.start_new_thread( _do_thread, ("thread_02",2,))
_thread.start_new_thread( _do_thread, ("thread_03",3,)) except:
print ("Error: 无法启动线程") while 1:
pass def _do_thread(name, delay): print("start thread %s " %(name)) #获取锁
lock.acquire() time.sleep(delay) print("%s: %s" % (name, time.ctime(time.time()))) #释放锁
lock.release()

9、模块化(测试主函数)

# -*- coding:utf-8 -*-
import test_module.t_string as t_s_module
import test_module.t_flow as t_f_module
import test_module.t_container as t_c_module
import test_module.t_file as t_f_module
import test_module.t_thread as t_t_module
import test_module.t_http as t_h_module
import test_module.t_class as t_c_module
import test_module.t_mysql as t_m_module #t_s_module._string_test_01()
#t_s_module._string_test_02()
#t_s_module._string_test_03()
#t_f_module._flow_test_01()
#print(t_f_module.status) #全局变量
#t_c_module._container_test_01()
#t_c_module._container_test_02()
#t_c_module._container_test_03()
#t_f_module._file_test_01()
#t_t_module._thread_test_01()
#t_h_module._http_test_01()
#t_c_module._class_test_01()
t_m_module._mysql_test_01()

源码文件附带如下:

http://files.cnblogs.com/files/Fredric-2013/python.rar

python 基础语法梳理的更多相关文章

  1. python 基础语法梳理(二)

    1.gevent使用 # -*- coding: utf-8 -*- import gevent import platform from gevent import subprocess def _ ...

  2. python之最强王者(2)——python基础语法

    背景介绍:由于本人一直做java开发,也是从txt开始写hello,world,使用javac命令编译,一直到使用myeclipse,其中的道理和辛酸都懂(请容许我擦干眼角的泪水),所以对于pytho ...

  3. Python 基础语法(三)

    Python 基础语法(三) --------------------------------------------接 Python 基础语法(二)------------------------- ...

  4. Python 基础语法(四)

    Python 基础语法(四) --------------------------------------------接 Python 基础语法(三)------------------------- ...

  5. Python 基础语法(二)

    Python 基础语法(二) --------------------------------------------接 Python 基础语法(一) ------------------------ ...

  6. Python 基础语法

    Python 基础语法 Python语言与Perl,C和Java等语言有许多相似之处.但是,也存在一些差异. 第一个Python程序 E:\Python>python Python 3.3.5 ...

  7. 吾八哥学Python(四):了解Python基础语法(下)

    咱们接着上篇的语法学习,继续了解学习Python基础语法. 数据类型大体上把Python中的数据类型分为如下几类:Number(数字),String(字符串).List(列表).Dictionary( ...

  8. python学习第五讲,python基础语法之函数语法,与Import导入模块.

    目录 python学习第五讲,python基础语法之函数语法,与Import导入模块. 一丶函数简介 1.函数语法定义 2.函数的调用 3.函数的文档注释 4.函数的参数 5.函数的形参跟实参 6.函 ...

  9. python学习第四讲,python基础语法之判断语句,循环语句

    目录 python学习第四讲,python基础语法之判断语句,选择语句,循环语句 一丶判断语句 if 1.if 语法 2. if else 语法 3. if 进阶 if elif else 二丶运算符 ...

随机推荐

  1. 开启irqbalance提升服务器性能

    操作系统 性能调休   公司有次压测存在一个问题:CPU资源压不上去,一直在40%已达到了性能瓶颈,后定位到原因,所在的服务器在压测过程中产生的中断都落在CPU0上处理,这种中断并没有均衡到各个CPU ...

  2. 全局唯一ID发号器的几个思路

    标识(ID / Identifier)是无处不在的,生成标识的主体是人,那么它就是一个命名过程,如果是计算机,那么它就是一个生成过程.如何保证分布式系统下,并行生成标识的唯一与标识的命名空间有着密不可 ...

  3. MonolithFirst

    As I hear stories about teams using a microservices architecture, I've noticed a common pattern. Alm ...

  4. 浅谈MySQL存储引擎-InnoDB&MyISAM

    存储引擎在MySQL的逻辑架构中位于第三层,负责MySQL中的数据的存储和提取.MySQL存储引擎有很多,不同的存储引擎保存数据和索引的方式是不同的.每一种存储引擎都有它的优势和劣势,本文只讨论最常见 ...

  5. 最短寻道优先算法----SSTF算法

    请珍惜小编劳动成果,该文章为小编原创,转载请注明出处. 该算法选择这样的进程,其要求访问的磁道与当前磁头所在的磁道距离最近,以使每次的寻道时间最短 java代码实现如下: import java.ut ...

  6. 学习笔记1--响应式网页+Bootstrap起步+全局CSS样式

    一.学习之前要了解一些背景知识: 在2g时代,3g时代,4g时代,早期的网页浏览设备,功能机,智能机.(本人最喜欢的透明肌,和古典黑莓机) 1.什么是响应式网页? Responsive Web Pag ...

  7. golang string和[]byte的对比

    golang string和[]byte的对比 为啥string和[]byte类型转换需要一定的代价?为啥内置函数copy会有一种特殊情况copy(dst []byte, src string) in ...

  8. BZOJ_2006_[NOI2010]超级钢琴_贪心+堆+ST表

    BZOJ_2006_[NOI2010]超级钢琴_贪心+堆+ST表 Description 小Z是一个小有名气的钢琴家,最近C博士送给了小Z一架超级钢琴,小Z希望能够用这架钢琴创作出世界上最美妙的 音乐 ...

  9. BZOJ_4518_[Sdoi2016]征途_斜率优化

    BZOJ_4518_[Sdoi2016]征途_斜率优化 Description Pine开始了从S地到T地的征途. 从S地到T地的路可以划分成n段,相邻两段路的分界点设有休息站. Pine计划用m天到 ...

  10. ELK---日志分析系统

    ELK就是一套完整的日志分析系统 ELK=Logstash+Elasticsearch+Kibana 统一官网https://www.elastic.co/products ELK模块说明 Logst ...