python入门
来源:互联网 发布:农村淘宝合伙人加盟 编辑:程序博客网 时间:2024/06/16 20:41
环境搭建
1、工具下载
python : https://www.python.org/downloads/
pycharm : https://www.jetbrains.com/pycharm/download/download-thanks.html?platform=windows
pycharm激活:http://blog.csdn.net/u013066730/article/details/56966966
2、 cmd运行
windows
配置环境变量
- 方法1
- 控制面板->系统->搞基系统设置->环境变量
- 选择用户变量TMP,在系统变量中找到Path,编辑,在尾部追加;,如;C:\Python27
- 方法2
- cmd命令行
- setx PATH “%PATH%;C:\Python27\”
- 备注:setx永久配置环境变量,set暂时配置环境变量(set PATH=%PATH%;C:\Python27)
测试方法
- 打开cmd,输入python,识别命令就OK
3、添加中文
Python 2.7.6 添加#-- coding: UTF-8 --
4、Python 2.7 和3.6 版本兼容性
print,为保证版本兼容性,建议使用print()来打印
查看版本
python -V
a="Hello Python"print(a) #both python 2.7和3.6print a #only python 2.7
基础积累
python文件的执行方式有两种:
- 1 先将模块中的内容编译成二进制语言,再去执行二进制语言。
- 2 省去编译步骤,执行速度更快。
- 1逻辑判断
- 满足多个条件
cond1 and cond2
- 满足多个条件之一
cond1 or cond2
- 特定值在列表中
item in list
- 特定值不在列表中
item not in list
- 满足多个条件
- 2 条件判断
if …
if … else…
if … elif … else …
#coding = utf-8score = 20if score >= 70: print("Good")elif score >= 60: print("及格")elif score>=30: print("不及格")else: print("很差")
- 3 循环
- for … else…
- while…else…
- for … else…
# range(min,max,step)for i in range(0,100): print("Item {0},{1}".format(i,"Hello"))else: print("i= 99,循环结束")
- 3 定义函数
python函数的输入参数和输出参数一样,可以没有也可以是多个,通过return来返回函数的输出值。函数的实现还会涉及到下面几个概念:
- 1 形参和实参
- 2 全局变量和局部变量
- 函数中如果没有进行全局变量声明,默认是局部变量。
- 3 文档字符串
- 定义:函数开头加上的一行函数的说明性的文字
- 查看方法:
- print functionname.doc
- help(functionname)
#----------------------- 函数输入和输出示例 -------------------#演示无返回值的函数实现def hello(): print("Hello World") print("Hello World 2")#演示传入参数只有一个返回值的函数实现def max(a,b): if(a > b): return a else: return bhello()print("The max is {0}".format(max(2,3)))#演示多个返回值的函数的实现def returnmultiparm(parm1,parm2) : res = parm1 * parm2 return (parm1,parm2,res)out = returnmultiparm(6,8)x,y,z=returnmultiparm(6,8)print ("the output is {0} first input {1} * second input {2} result {3} ".format(out,x,y,z))#----------------------- 函数输入和输出示例 -------------------
#----------------------- 局部和全局变量示例 -------------------#-*- coding: UTF-8 -*-def scope(): i = 7 return ij = scope()i = 9 #局部变量k = scope()print ("before change {0} variable {1} after change {2}".format(j,i,k))def globaldemo(): global g #全局变量,作用域为自声明之后的代码行 g = 7 return gh = globaldemo()g = 9;s = globaldemo()print ("before change {0} variable {1} after change {2}".format(h,g,s))g = 9print ("after rechange variable {0}".format(g))#----------------------- 局部和全局变量示例 -------------------
#---------------------- 文档字符串示例 --------------------------def mutil(i,j): '''实现法运算 :param i:乘数1 :param j:乘数2 :return: 返回i乘以j的结果 ''' k = i * j return kprint("mutil的文档字符串 {0}".format(mutil.__doc__))#help(mutil)#---------------------- 文档字符串示例 --------------------------
- 4 面向对象编程
class Hello: def __init__(self,name): #构造函数 self.name = name def sayHello(self): print("Hello Python") print("Hello {0}".format(self.name))#继承class Hi(Hello): def __init__(self,name): Hello.__init__(self,name) def sayHi(self): print("Hi {0}".format(self.name))h = Hello("Injoy")h.sayHello()h0 = Hi("ZhangSan")h0.sayHi()
- 5 pickle腌制
Python中对一些对象需要持久存储,且不丢失这个对象的类型和数据,便需要对这些数据进行序列化,序列化之后需要使用时,再恢复为原来的数据。序列化的过程,称之为pickcle(腌制),而反过来的过程称之为反pickle
import pickle# -*- coding: UTF-8 -*-a = ["mingyue", "jishi", "you"]# dumps(object)将对象序列化b = pickle.dumps(a)print("原数据为 {0}".format(a))print("腌制的结果 {0}".format(b))# loads(string)将对象恢复原样,且对象保持为原来格式c = pickle.loads(b)print("反腌制的结果是 {0}".format(c))# dump(object,file)将对象存储到文件里面序列化a1=["bajiu", "wen", "qinghuan"]f1 = file('pickle.pk1', 'wb')pickle.dump(a1, f1)f1.close()# load(object,file)将dump存储在文件中的数据恢复f2 = file('pickle.pk1', 'rb')b1 = pickle.load(f2)print("反腌制的结果是 {0}".format(b1))f2.close()
- 6 模块
实现一项或者多想功能的程序块,是函数功能的扩展。模块要比函数的功能广,在模块中可以重用多个函数。
- 1 导入模块
- import modelname
- 2 字节编译:把模块编译成二进制语言的过程,该过程会生成模块对应的.pyc文件,该过程是在解释器中完成的,python是解释性语言。
- .pyc文件:经过编译后模块对应的二进制文件。
- 如何生成.pyc文件
- import zipfile
- cmd命令行 python -m compileall zipfile.py
- .pyc文件的作用
- 加快模块的运行速度(无须编译)
- 可以进行反编译等高级功能
- 如何使用
- -
- 如何生成.pyc文件
- .pyc文件:经过编译后模块对应的二进制文件。
- 3 from … import …
- from sys import version #导入sys模块和version方法
- from sys import * #导入sys模块的所有的方法
- 4 name属性
- name的值是main对应模块是主模块,否则是其他的值
- 5 dir()函数
- 查看指定模块的功能列表
- 查看任意指定的对象的功能列表
#-*- coding: UTF-8 -*-#---------------------- 导入模块示例 ---------------------import mathimport syspi = math.piprint ("Pi = {0}".format(pi))version = sys.version #查看版本信息path = sys.executable #返回当前目录win = sys.getwindowsversion() #获取windows的版本信息modelused = sys.modules.keys() #已经导入的模块信息print ("Version: {0}\n executable path: {1}\nWindows info: {2}\nmodel has been used:{3}".format(version,path,win,modelused))#---------------------- 导入模块示例 ---------------------
form…import示例#-*- coding: UTF-8 -*-#---------------------- form...import...示例 ---------------------from sys import version #导入sys模块和version方法from sys import *versionexecutableprint ("Version {0}".format(version))#---------------------- form...import...示例 ---------------------
#lib.pyclass Hello: def sayHello(self): print("Hello Python")
import libh = lib.Hello();h.sayHello()from lib import Helloh=Hello()h.sayHello()
import syss = dir(sys)print ("{0}".format(s))d=[]d = dir(d)print {"{0}".format(d)}
- 7 常量和变量
- 变量
- 即赋值,即修改
- 常量
- 一单绑定便不能更改
- Python常量的实现需要以对象的方式实现
在Lib/下新建const.py(3.6版本不支持,2.7.6的版本支持),相关实现如下
- 常量
- 即赋值,即修改
- 变量
class _const(object): class ConstError(TypeError):pass def __setattr__(self, name, value): if self.__dict__.has_key(name): raise self.ConstError,"Can not rebind const (%s)" % name self.__dict__[name] = value def __delattr__(self, item): if name in self.__dict__: raise self.ConstError,"Can not unbind const(%s)" % name raise NameError,nameimport syssys.modules[__name__] = _const()
import constconst.value=5print const.valueconst.value=6
运行结果如下,表明,Python的常量一旦绑定,无法修改
Traceback (most recent call last): File "D:/01-project/code/02-python/untitled/base.py", line 5, in <module> const.value=6 File "C:\Python27\lib\const.py", line 6, in __setattr__ raise self.ConstError,"Can not rebind const (%s)" % nameconst.ConstError: Can not rebind const (value)
数据类型
基本的数据类型
- 1 有符号整形 int,如-1,1009等等
- 2 长整型 long,如8788l等等
- 3 浮点型 float,如0.1等等
- 4 布尔型 bool,True,False
- 5 复数型 complex ,如4+2j等等
字符串:单引号、双引号、三引号
表示方式
- 1 单引号内可以使用双引号,且可以输出
- 2 双引号内部可使用单引号,但是不可使用双引号,单引号和双引号可以交替用
- 3 三引号内部的字符串可以换行
使用方式
- 1 字符串重复
“<string>”*times
- 2 子字符串,其运算方法:索引运算方法[]、切片运算方法[:]
- 3 修改字符串的大小写
- title():首字母大写方式显示
- upper():将字符串全部大写显示
- lower():将字符串全部小写显示
- 4 合并字符串(+)
- 5 转义字符
- 换行符 \n
- 制表符 \t
- 6 自然字符串:在字符前面加上r来保持转义字符的原意
- 7 剔除空格
- lstrip()剔除字符串开头的空格
- rstrip()剔除字符串末尾的空格
- strip()剔除字符串开头和末尾的空格
c1='Hello'print c1c2='Hello World "HaHaHa"'print c2c1="Hello2"print c1c2="It's a dog"print c2c1='''Hello World !secomd'''print c1
print 'It\'s a dog'print "Hello World\nHelloWorld"print r"Hello World\nHelloWorld"print "Hello World"*5c1="HelloPython"c2=c1[0]c3=c1[7]c4=c1[:2]c5=c1[2:]c6=c1[2:7]print(c2)print(c3)print(c4)print(c5)print(c6)
name = "ada loveAce"print(name.title())print(name.upper())print(name.lower())firstName = "ada"secondName = "loveace"fullName = firstName + " " + secondNameprint(fullName)name = " python"print("name = {0}".format(name.lstrip()))name2 = "python "print("name2 = {0}".format(name2.rstrip()))name3 = " pyhton "print("name3 = {0}".format(name3.strip()))
执行结果
Ada LoveaceADA LOVEACEada loveaceada loveacename = pythonname2 = pythonname3 = pyhton
数据结构
内置数据结构
列表
- 存储一连串元素的容器
- 用[]表示,用,来分割其中的元素,其中的元素可修改
- 元素操作
- 元素访问
- 通过序列号0~n可以访问第一个到第n+1个元素。
- 通过负数索引-1~-n个元素,-1返回最后一个元素,以此类推
- 元素切片,类似于字符串切片
- 修改元素
c[n] = ....
- 添加元素
- 元素追加
append()
- 在某个位置插入新元素
insert(i,parm)
- 在列表尾部追加另一个包含多个元素的列表
alist.extend(blist)
- 元素追加
- 删除某个元素
- 删除元素之后不再使用
- 删除某个元素
del param[index]
- 删除某个元素
- 删除元素之后会再次使用
- 删除尾部元素
param.pop()
- 删除某个位置的元素
param.pop(index)
- 依据值删除元素
param.remove(name)
- 删除尾部元素
- 删除元素之后不再使用
- 复制列表“`dst = src[:]
- 元素访问
- 组织列表
- 永久排序
- sort()按照字母顺序进行排序
- sort(reverse=True)按照字母逆向排序
- 临时排序
- 保持元素原来的顺序,同时一特定的书序来呈现
- 按照字母顺序呈现,sorted()
- 按照字母逆向顺序呈现,sorted(list,reverse=True)
- 反转元素列表,永久性操作,可以再次反转实现恢复。reverse()
- 永久排序
- 列表长度
- len()可以快速获取列表的长度
- 列表遍历
item in list
- 数字列表
- range(n,m,step)生成从n到m-1的步进为step的一系列的数字
- list(range())生成一串数字列表
c=["lily",'jone','joy']print ("third {0} sencond {1}".format(c[2],c[-2]))#修改元素c[2]="Change"print ("chang sencond parm {0}".format(c[2]))#尾部添加元素c.append("Lucy")print("append {0}".format(c))#某个位置插入新元素c.insert(1,"Angle")print("insert in 1 {0}".format(c))#在尾部追加列表a = ["abc","efgh","dfg"]b = ["xyz","hij"]a.extend(b)print(a)#删除某个元素del(c[0])print("delete first {0}".format(c))#删除末尾元素,并可以接着使用其值(应用于删除元素加入到非活跃列表)popParm = ['Honda','Yamaha','Suzuki']last = popParm.pop()print("The last parameter is {0}".format(last))#删除任意位置的元素,并可以接着使用其值i = 1popedParm = popParm.pop(i)print("pop {0} parameter {1}".format(i,popedParm))#根据元素内容删除popParm = ['Honda','Yamaha','Suzuki']popedParm= popParm.remove("Yamaha")print("remove Yamaha {0}".format(popParm))#组织列表parm = ['Yamaha','Honda','Suzuki']parm.sort()print(parm)parm.sort(reverse=True)print(parm)
parm = ['Yamaha','Honda','Suzuki']print("sorted in order {0} original {1} sorted in reverse order {2}".format(sorted(parm),parm,sorted(parm,reverse=True)))parm = ['Yamaha','Honda','Suzuki']parm.reverse()print("reverse {0}".format(parm))parm.reverse()print("reverse again {0}".format(parm))
运行结果
sorted in order ['Honda', 'Suzuki', 'Yamaha'] original ['Yamaha', 'Honda', 'Suzuki'] sorted in reverse order ['Yamaha', 'Suzuki', 'Honda']reverse ['Suzuki', 'Honda', 'Yamaha']reverse again ['Yamaha', 'Honda', 'Suzuki']
parm = ['Yamaha','Honda','Suzuki']print(len(parm)) #3
#列表遍历firends = ["Lily","Lucy","Anna"]for firend in firends: print(firend + " is my firend.")
#数字列表生成和初步解析#生成1到1000000的数字列表,并求和、最大值和最小值num = list(range(1,1000001))numSum = sum(num)min = min(num)max = max(num)print("sum = %u min = %u max = %u " % (numSum,min,max))#1到10的立方squares = [value**3 for value in range(1,11)]for item in squares: print(item)
元组
- 用()来表示,其中的元素不可修改,只能读取,不可更改的列表
- 列表中的元素可以修改,而元组不可以,只能读取
- 遍历和列表一致
#实验修改元组元素的值c2=("lily",'jone','joy')print (c2[2]) #joy#TypeError: 'tuple' object does not support item assignmentc2[2]="chage" #errorprint (c2[2])
#元组赋值和遍历元组data = (100,200,800,999)for dataitem in data: print(dataitem)
字典
- 也叫关联数组,是一种动态结构,可以随时向其中添加键值对,用{}表示,内置数据结构
- 字典操作
- 创建空的字典
dict = {}
- 添加某字典到指定的字典
dict.update(dict2)
- 删除键值对
del dict[key]
- 遍历,遍历,和键-值对的存储顺序无关。
items()
返回键-值对列表,keys()
遍历字典中所有的键,遍历,默认会遍历所有的键值values()
遍历字典所有元素的值set()
集合,可剔除元素中重复的值,保留独一无二的值
- 将字典转化为列表
- items()将字典中的每个项分别做为元组,添加到列表中,形成一个列表容器
- 由类似对象组成的字典
- 创建空的字典
- 嵌套
- 字典列表
- 列表字典
- 字典中存储字典
#-*- coding: UTF-8 -*-d = {"名字" : "Jone", "籍贯" : "桂林"}print("名字:{0}".format(d["名字"]))print("籍贯:{0}".format(d['籍贯']))#向字典中添加元素d['爱好'] = 'Music'print("爱好:{0}".format(d['爱好']))#修改字典中元素的值d['爱好'] = "Reading"print("爱好:{0}".format(d['爱好']))#删除键值对del d["爱好"]print(d)
favorite = { 'joy' : 'python', 'liyi' : 'C', 'lucy' : 'C++', 'aha' : 'python',}#字典遍历键-值对for key, value in favorite.items(): print("Name %s Language %s" % (key.title(), value.title()))#遍历字典中所有的键print("All the keys is ")for keyName in favorite.keys(): print(keyName.title())print("The same as above ")for keyname in favorite: print(keyname.title())#顺序遍历字典中所有的键print("Sorted name ")for sortedName in sorted(favorite.keys()): print(sortedName)#遍历字典中所有的值print("All the values :")for value in favorite.values(): print(value.title())#剔除重复元素,保留独一无二的值print("Different value :")for difValue in set(favorite.values()): print(difValue)
#添加某字典到指定的字典dict1 = {'Name':"Lily",'Age': 7}dict2 = {"sex" : 'female'}dict1.update(dict2)print(dict1)#print("%s " % dict1)#结果:{'Name': 'Lily', 'Age': 7, 'sex': 'female'}
#将字典转化为列表dict1 = {'Name': "Lily", 'Age': 7}item = dict1.items()print(item)#结果:dict_items([('Name', 'Lily'), ('Age', 7)])
#由类似对象组成的字典,元素值访问favorite = { 'joy' : 'python', 'liyi' : 'C', 'lucy' : 'C++', 'aha' : 'Ruby',}print("Joy's favorite languange is " + favorite['joy'].title())
#字典列表alien0_0 = {'color' : "green",'points' : 5}alien0_1 = {'color' : "yellow",'points' : 6}alien0_2 = {'color' : "red",'points' : 8}aliens = [alien0_0, alien0_1, alien0_2]for alien in aliens: print(alien)#列表字典pizza = { 'crust' : 'thick', 'topppings' : ['mushrooms', 'extra cheese'],}print("You order a " + pizza['crust'] + "curst pizza:")for topping in pizza['topppings']: print("\t" + topping)
#字典列表alien0_0 = {'color' : "green",'points' : 5}alien0_1 = {'color' : "yellow",'points' : 6}alien0_2 = {'color' : "red",'points' : 8}aliens = [alien0_0, alien0_1, alien0_2]for alien in aliens: print(alien)#列表字典pizza = { 'crust' : 'thick', 'topppings' : ['mushrooms', 'extra cheese'],}print("You order a " + pizza['crust'] + "curst pizza:")for topping in pizza['topppings']: print("\t" + topping)#字典中嵌套字典infos = { "joy" : { "first" : "albert", "location" : "paris", "labguage" : "english", }, "lucy" : { "first" : "maire", "location" : "london", "labguage" : "Japanese", },}print("The stored information is\n")for key, value in infos.items(): print("\t" + key.title()) for key_key, key_value in value.items(): print(key_key.title() + ":\t"+ key_value.title())
- 3 扩展数据结构之栈
class Stack(): def __init__(self,size): self.Stack = [] self.top = -1 self.size = size def pop(self): if self.empty(): print ("The stack is Empty.") else: self.top = self.top - 1 def push(self,data): if self.full(): print ("The stack is full") else: self.Stack.append(data) self.top = self.top + 1 def empty(self): if self.top == -1: return True else: return False def full(self): if self.top == self.size - 1: return True else: return Falsetest = Stack(2)te = test.empty()print ("empty {0}".format(te))test.push(0)test.push(1)te = test.empty()tf = test.full()print ("push twice : empty {0} Full {1}".format(te,tf))test.pop()te = test.empty()tf = test.full()print ("pop once : empty {0} Full {1}".format(te,tf))test.pop()te = test.empty()tf = test.full()print ("pop twice : empty {0} Full {1}".format(te,tf))
- 4 扩展数据结构之队列
class Queue(): def __init__(self,size): self.queue = [] self.size = size self.head = -1 self.tail = -1 def empty(self): if self.head == self.tail: return True else: return False def full(self): if self.tail - self.head == self.size: return True else: return False def enQueue(self,data): if self.full(): print ("The Queue is full") else: self.tail = self.tail + 1 self.queue.append(data) def unQueue(self): if self.empty(): print ("The queue is empty") else: self.head = self.head + 1test = Queue(2)te = test.empty()print ("Empty {0}".format(te))test.enQueue(0)test.enQueue(1)te = test.empty()tf = test.full()print ("Empty {0} Full {1}".format(te,tf))test.unQueue()te = test.empty()tf = test.full()print ("Empty {0} Full {1}".format(te,tf))test.unQueue()te = test.empty()tf = test.full()print ("Empty {0} Full {1}".format(te,tf))
- 3 集合,格式是set(元素),其有两个功能
- 简历关系
- 消除重复元素
a=set("HelloPython")b=set("Hefg")#求交集c= a&bprint c#求并集d=a|bprint d#求差e=a-bprint e#消除重复元素new=set(a)print new
异常捕捉
- 1 捕捉所有异常
try : a = b b = cexcept Exception,e: print Exception,"is",e
<type 'exceptions.Exception'> is name 'b' is not defined
- 2 用traceback模块查看异常
import tracebacktry : a = b b = cexcept Exception,e: traceback.print_exc()
Traceback (most recent call last): File "E:/makeup/01-code/01-pyhton/02-webworm/def.py", line 3, in <module> a = bNameError: name 'b' is not defined
- 3 用sys模块回溯异常
import systry: a = b b = cexcept: info = sys.exc_info() print (info)
(<type 'exceptions.NameError'>, NameError("name 'b' is not defined",), <traceback object at 0x02B2E580>)
- 4 将traceback模块的异常保存进文件
import tracebacktry : a = b b = cexcept: f = open("log.txt",'a') traceback.print_exc(file=f) f.flush() f.close()
附录
编译错误
- 1 TypeError: must be str, not int
age = 23message = "Happy " + age + "rd Birthday"#message = "Happy " + str(age) + "rd Birthday"print(message)
问题:无法确定age代表的是23还是2或3的字符
修正方法:用str()将非字符串转化为字符串
- 2 TypeError: ‘tuple’ object does not support item assignment
c2=("lily",'jone','joy')print (c2[2]) #joy#TypeError: 'tuple' object does not support item assignmentc2[2]="chage" #errorprint (c2[2])
问题:元组的值无法修改
- 5 扩展数据结构之树
web2py
利用python进行网站开发。python3.6不支持web2py,python 2.7.6支持。创建工程时,默认会到http://web2py.com/init/default/download下载源文件,放在工程目录的web2py下,整个程序执行的脚本是web2py/web2py.py
1 静态文件
位于工程目录下,web2py\applications\MyFirstWeb\static,可以直接进行img,html文件的修改和新建。之后均可以在网页进行访问,如:http://127.0.0.1:8000/MyFirstWeb/static/images/facebook.png可以访问到相应的图片。
2 控制器
位于工程目录下,web2py\applications\MyFirstWeb\controllers
写控制器示例,在控制器目录下新建hello.py文件,控制器处理的默认的方法是index,用户可以通过自定义的方法来进行设计,如示例程序中的hello()。
#coding = utf-8def index(): return "Hello Python"def hello(): return "Hello,out of index"
访问http://127.0.0.1:8000/MyFirstWeb/hello,可以看到Hello Python
访问http://127.0.0.1:8000/MyFirstWeb/hello/hello,可以看到Hello,out of index
- Python入门
- python入门
- Python入门
- Python入门
- Python入门
- Python入门
- python入门
- Python入门
- Python 入门
- Python入门
- python入门
- Python入门
- python入门
- python入门
- Python入门
- python 入门
- python入门
- python入门
- 【数据结构和算法】Day 13
- Expected response code 220 but got code “”, with message “””
- POJ 1789 Truck History
- 多维动态规划——洛谷P1006 传纸条
- tensorflow笔记(四)之MNIST手写识别系列一
- python入门
- ASP.NET Core
- 设计模式的应用场景(6)--外观模式
- 11.C++调用Lua全局变量(表)
- stream_socket_enable_crypto(): this stream does not
- Number Sequence
- 使用SMTP发送邮件报错:Expected response code 250 but got code "553", with message "553 Envolope sender mis...
- hdu 6181 Two Paths(最短路,spfa)
- bzoj1597 [Usaco2008 Mar]土地购买