本节内容2016-05-30php
1、Ptyhon介绍html
Python诞生于1989年圣诞节期间,创始人吉多•范罗苏姆(Guido Van Gossum)。java
最新TIOBE排行榜(http://www.tiobe.com/tiobe_index?page=index),Python赶超PHP占据第五,Python崇尚优美、清晰、简单,是一个优秀并普遍使用的语言。python
Python能够应用于众多领域:数据分析、组件集成、网络服务、图像处理、数值计算和科室计算等。linux
目前几乎全部在中型互联网企业都在使用Pthon:Youtube、Dropbox、BT、Quora(中国知乎)、Google、Yahoo!、Facebook、NASA、百度、腾讯、汽车之家、美团等。ios
目前Python主要应用领域:c++
Python在一些公司的应用: web
为何是Python而不是其余语言?算法
C 和 Python、Java、C#等shell
C语言: 代码编译获得 机器码 ,机器码在处理器上直接执行,每一条指令控制CPU工做
其余语言: 代码编译获得 字节码 ,虚拟机执行字节码并转换成机器码再后在处理器上执行
Python 和 C Python这门语言是由C开发而来
对于使用:Python的类库齐全而且使用简洁,若是要实现一样的功能,Python 10行代码能够解决,C可能就须要100行甚至更多.
对于速度:Python的运行速度相较与C,绝逼是慢了
Python 和 Java、C#等
对于使用:Linux原装Python,其余语言没有;以上几门语言都有很是丰富的类库支持
对于速度:Python在速度上可能稍显逊色
因此,Python和其余语言没有什么本质区别,其余区别在于:擅长某领域、人才丰富、先入为主。
Python的种类
Python的官方版本,使用C语言实现,使用最为普遍,CPython实现会将源文件(py文件)转换成字节码文件(pyc文件),而后运行在Python虚拟机上。
Python的Java实现,Jython会将Python代码动态编译成Java字节码,而后在JVM上运行。
Python的C#实现,IronPython将Python代码编译成C#字节码,而后在CLR上运行。(与Jython相似)
Python实现的Python,将Python的字节码字节码再编译成机器码。
In summary : Python 2.x is legacy, Python 3.x is the present and future of the language
Python 3.0 was released in 2008. The final 2.x version 2.7 release came out in mid-2010, with a statement of
extended support for this end-of-life release. The 2.x branch will see no new major releases after that. 3.x is
under active development and has already seen over five years of stable releases, including version 3.3 in 2012,
3.4 in 2014, and 3.5 in 2015. This means that all recent standard library improvements, for example, are only
available by default in Python 3.x.
Guido van Rossum (the original creator of the Python language) decided to clean up Python 2.x properly, with less regard for backwards compatibility than is the case for new releases in the 2.x range. The most drastic improvement is the better Unicode support (with all text strings being Unicode by default) as well as saner bytes/Unicode separation.
Besides, several aspects of the core language (such as print and exec being statements, integers using floor division) have been adjusted to be easier for newcomers to learn and to be more consistent with the rest of the language, and old cruft has been removed (for example, all classes are now new-style, "range()" returns a memory efficient iterable, not a list as in 2.x).
PRINT IS A FUNCTION
The statement has been replaced with a print() function, with keyword arguments to replace most of the special syntax of the old statement (PEP 3105). Examples:
1 Old: print "The answer is", 2*2 New: print("The answer is", 2*2) 2 Old: print x, # Trailing comma suppresses newline New: print(x, end=" ") # Appends a space instead of a newline 3 Old: print # Prints a newline 4 New: print() # You must call the function! 5 Old: print >>sys.stderr, "fatal error" New: print("fatal error", file=sys.stderr) 6 Old: print (x, y) # prints repr((x, y)) 7 New: print((x, y)) # Not the same as print(x, y)!
You can also customize the separator between items, e.g.:
1 print("There are <", 2**32, "> possibilities!", sep="")
ALL IS UNICODE NOW
还能够这样玩: (A,*REST,B)=RANGE(5)
1 <strong>>>> a,*rest,b = range(5) 2 >>> a,rest,b 3 (0, [1, 2, 3], 4) 4 </strong>
某些库更名了
Old Name |
New Name |
_winreg |
winreg |
ConfigParser |
configparser |
copy_reg |
copyreg |
Queue |
queue |
SocketServer |
socketserver |
markupbase |
_markupbase |
repr |
reprlib |
test.test_support |
test.support |
还有谁不支持PYTHON3?
One popular module that don't yet support Python 3 is Twisted (for networking and other applications). Most
actively maintained libraries have people working on 3.x support. For some libraries, it's more of a priority than
others: Twisted, for example, is mostly focused on production servers, where supporting older versions of
Python is important, let alone supporting a new version that includes major changes to the language. (Twisted is
a prime example of a major package where porting to 3.x is far from trivial
1、下载安装包 https://www.python.org/downloads/ 2、安装 默认安装路径:C:\python27 3、配置环境变量 【右键计算机】--》【属性】--》【高级系统设置】--》【高级】--》【环境变量】--》【在第二个内容框中找到 变量名为Path 的一行,双击】 --> 【Python安装目录追加到变值值中,用 ; 分割】 如:原来的值;C:\python27,切记前面有分号
linux、Mac
无需安装,原装Python环境 ps:若是自带2.6,请更新至2.7
在linux 下建立一个文件叫hello.py,并输入
print("Hello world!")
而后执行命令:python hello.py ,输出
$ vim hello.py
$ python hello.py
Hello world!
如此一来,执行: ./hello.py
便可。
ps:执行前需给予 hello.py 执行权限,chmod 755 hello.py
1 [root@test ~]# python 2 Python 2.7.11 (default, May 17 2016, 14:00:45) 3 [GCC 4.4.6 20110731 (Red Hat 4.4.6-3)] on linux2 4 Type "help", "copyright", "credits" or "license" for more information. 5 >>> print("Hello world!") 6 Hello world!
对比下其它语言的hello world
1 #include <iostream> 2 int main(void) 3 { 4 std::cout<<"Hello world"; 5 }
1 #include <stdio.h> 2 int main(void) 3 { 4 printf("\nhello world!"); 5 return 0; 6 }
1 public class HelloWorld{ 2 // 程序的入口 3 public static void main(String args[]){ 4 // 向控制台输出信息 5 System.out.println("Hello World!"); 6 } 7 }
1 <?php 2 echo "hello world!"; 3 ?>
1 puts "Hello world."
1 package main 2 3 import "fmt" 4 5 func main(){ 6 7 fmt.Printf("Hello World!\n God Bless You!"); 8 9 }
Variables are used to store information to be referenced and manipulated in a computer program. They also provide a way of labeling data with a descriptive name, so our programs can be understood more clearly by the reader and ourselves. It is helpful to think of variables as containers that hold information. Their sole purpose is to label and store data in memory. This data can then be used throughout your program.
声明变量
#_*_coding:utf-8_*_ name = "Shawn Yu"
上述代码声明了一个变量,变量名为: name,变量name的值为:"Shawn Yu"
变量定义的规则:
name = "Shawn Li" name2 = name print(name,name2) name = "Jack" print("What is the value of name2 now?")
python解释器在加载 .py 文件中的代码时,会对内容进行编码(默认ascill)
ASCII(American Standard Code for Information Interchange,美国标准信息交换代码)是基于拉丁字母的一套电脑编码系统,主要用于显示现代英语和其余西欧语言,其最多只能用 8 位来表示(一个字节),即:2**8 = 256-1,因此,ASCII码最多只能表示 255 个符号。
显然ASCII码没法将世界上的各类文字和符号所有表示,因此,就须要新出一种能够表明全部字符和符号的编码,即:Unicode
Unicode(统一码、万国码、单一码)是一种在计算机上使用的字符编码。Unicode 是为了解决传统的字符编码方案的局限而产生的,它为每种语言中的每一个字符设定了统一而且惟一的二进制编码,规定虽有的字符和符号最少由 16 位来表示(2个字节),即:2 **16 = 65536,
注:此处说的的是最少2个字节,可能更多
UTF-8,是对Unicode编码的压缩和优化,他再也不使用最少使用2个字节,而是将全部的字符和符号进行分类:ascii码中的内容用1个字节保存、欧洲的字符用2个字节保存,东亚的字符用3个字节保存...
因此,python解释器在加载 .py 文件中的代码时,会对内容进行编码(默认ascill),若是是以下代码的话:
报错:ascii码没法表示中文
1 #!/usr/bin/env python 2 3 print "你好,世界"
改正:应该显示的告诉python解释器,用什么编码来执行源代码,即:
1 #!/usr/bin/env python 2 # -*- coding: utf-8 -*- 3 4 print "你好,世界"
当行注视:# 被注释内容
多行注释:""" 被注释内容 """
1 #!/usr/bin/env python 2 #_*_coding:utf-8_*_ 3 4 5 #name = raw_input("What is your name?") #only on python 2.x 6 name = input("What is your name?") 7 print("Hello " + name )
输入密码时,若是想要不可见,须要利用getpass 模块中的 getpass方法,即:
1 #!/usr/bin/env python 2 # -*- coding: utf-8 -*- 3 4 import getpass 5 6 # 将用户输入的内容赋值给 name 变量 7 pwd = getpass.getpass("请输入密码:") 8 9 # 打印输入的内容 10 print(pwd)
Python的强大之处在于他有很是丰富和强大的标准库和第三方库,几乎你想实现的任何功能都有相应的Python库支持,之后的课程中会深刻讲解经常使用到的各类库,如今,咱们先来象征性的学2个简单的。
sys
1 #!/usr/bin/env python 2 # -*- coding: utf-8 -*- 3 4 import sys 5 6 print(sys.argv) 7 8 9 #输出 10 $ python test.py helo world 11 ['test.py', 'helo', 'world'] #把执行脚本时传递的参数获取到了
os
1 #!/usr/bin/env python 2 # -*- coding: utf-8 -*- 3 4 import os 5 6 os.system("df -h") #调用系统命令
彻底结合一下
1 import os,sys 2 3 os.system(''.join(sys.argv[1:])) #把用户的输入的参数看成一条命令交给os.system来执
本身写个模块
python tab补全模块
1. Python是一门解释型语言?
我初学Python时,听到的关于Python的第一句话就是,Python是一门解释性语言,我就这样一直相信下去,直到发现了*.pyc文件的存在。若是是解释型语言,那么生成的*.pyc文件是什么呢?c应该是compiled的缩写才对啊!
为了防止其余学习Python的人也被这句话误解,那么咱们就在文中来澄清下这个问题,而且把一些基础概念给理清。
2. 解释型语言和编译型语言
计算机是不可以识别高级语言的,因此当咱们运行一个高级语言程序的时候,就须要一个“翻译机”来从事把高级语言转变成计算机能读懂的机器语言的过程。这个过程分红两类,第一种是编译,第二种是解释。
编译型语言在程序执行以前,先会经过编译器对程序执行一个编译的过程,把程序转变成机器语言。运行时就不须要翻译,而直接执行就能够了。最典型的例子就是C语言。
解释型语言就没有这个编译的过程,而是在程序运行的时候,经过解释器对程序逐行做出解释,而后直接运行,最典型的例子是Ruby。
经过以上的例子,咱们能够来总结一下解释型语言和编译型语言的优缺点,由于编译型语言在程序运行以前就已经对程序作出了“翻译”,因此在运行时就少掉了“翻译”的过程,因此效率比较高。可是咱们也不能一律而论,一些解释型语言也能够经过解释器的优化来在对程序作出翻译时对整个程序作出优化,从而在效率上超过编译型语言。
此外,随着Java等基于虚拟机的语言的兴起,咱们又不能把语言纯粹地分红解释型和编译型这两种。
用Java来举例,Java首先是经过编译器编译成字节码文件,而后在运行时经过解释器给解释成机器文件。因此咱们说Java是一种先编译后解释的语言。
3. Python究竟是什么
其实Python和Java/C#同样,也是一门基于虚拟机的语言,咱们先来从表面上简单地了解一下Python程序的运行过程吧。
当咱们在命令行中输入python hello.py时,实际上是激活了Python的“解释器”,告诉“解释器”:你要开始工做了。但是在“解释”以前,其实执行的第一项工做和Java同样,是编译。
熟悉Java的同窗能够想一下咱们在命令行中如何执行一个Java的程序:
javac hello.java
java hello
只是咱们在用Eclipse之类的IDE时,将这两部给融合成了一部而已。其实Python也同样,当咱们执行python hello.py时,他也同样执行了这么一个过程,因此咱们应该这样来描述Python,Python是一门先编译后解释的语言。
4. 简述Python的运行过程
在说这个问题以前,咱们先来讲两个概念,PyCodeObject和pyc文件。
咱们在硬盘上看到的pyc天然没必要多说,而其实PyCodeObject则是Python编译器真正编译成的结果。咱们先简单知道就能够了,继续向下看。
当python程序运行时,编译的结果则是保存在位于内存中的PyCodeObject中,当Python程序运行结束时,Python解释器则将PyCodeObject写回到pyc文件中。
当python程序第二次运行时,首先程序会在硬盘中寻找pyc文件,若是找到,则直接载入,不然就重复上面的过程。
因此咱们应该这样来定位PyCodeObject和pyc文件,咱们说pyc文件实际上是PyCodeObject的一种持久化保存方式。
2 是一个整数的例子。
长整数 不过是大一些的整数。
3.23和52.3E-4是浮点数的例子。E标记表示10的幂。在这里,52.3E-4表示52.3 * 10-4。
(-5+4j)和(2.3-4.6j)是复数的例子。
int(整型)
"hello world"
1 name = "shawn" 2 print "i am %s " % name 3 4 #输出: i am shawn
PS: 字符串是 %s;整数 %d;浮点数%f
1 name_list = ['alex', 'seven', 'eric'] 2 或 3 name_list = list(['alex', 'seven', 'eric'])
基本操做:
1 ages = (11, 22, 33, 44, 55) 2 或 3 ages = tuple((11, 22, 33, 44, 55))
1 person = {"name": "mr.wu", 'age': 18} 2 或 3 person = dict({"name": "mr.wu", 'age': 18})
经常使用操做:
场景1、用户登录验证
1 # 提示输入用户名和密码 2 3 # 验证用户名和密码 4 # 若是错误,则输出用户名或密码错误 5 # 若是成功,则输出 欢迎,XXX! 6 7 8 #!/usr/bin/env python 9 # -*- coding: encoding -*- 10 11 import getpass 12 13 14 name = raw_input('请输入用户名:') 15 pwd = getpass.getpass('请输入密码:') 16 17 if name == "alex" and pwd == "cmd": 18 print("欢迎,alex!") 19 else: 20 print("用户名和密码错误")
场景2、猜年龄游戏
在程序里设定好你的年龄,而后启动程序让用户猜想,用户输入后,根据他的输入提示用户输入的是否正确,若是错误,提示是猜大了仍是小了
1 #!/usr/bin/env python 2 # -*- coding: utf-8 -*- 3 4 5 my_age = 28 6 7 user_input = int(input("input your guess num:")) 8 9 if user_input == my_age: 10 print("Congratulations, you got it !") 11 elif user_input < my_age: 12 print("Oops,think bigger!") 13 else: 14 print("think smaller!")
最简单的循环10次
1 #_*_coding:utf-8_*_ 2 __author__ = 'Alex Li' 3 4 5 for i in range(10): 6 print("loop:", i )
输出:
1 loop: 0 2 loop: 1 3 loop: 2 4 loop: 3 5 loop: 4 6 loop: 5 7 loop: 6 8 loop: 7 9 loop: 8 10 loop: 9
需求一:仍是上面的程序,可是遇到小于5的循环次数就不走了,直接跳入下一次循环
1 for i in range(10): 2 if i<5: 3 continue #不往下走了,直接进入下一次loop 4 print("loop:", i )
需求二:仍是上面的程序,可是遇到大于5的循环次数就不走了,直接退出
1 for i in range(10): 2 if i>5: 3 break #不往下走了,直接跳出整个loop 4 print("loop:", i )
有一种循环叫死循环,一经触发,就运行个天荒地老、海枯石烂。
海枯石烂代码
1 count = 0 2 while True: 3 print("你是风儿我是沙,缠缠绵绵到天涯...",count) 4 count +=1
其实除了时间,没有什么是永恒的,死loop仍是少写为好
上面的代码循环100次就退出吧
1 count = 0 2 while True: 3 print("你是风儿我是沙,缠缠绵绵到天涯...",count) 4 count +=1 5 if count == 100: 6 print("去你妈的风和沙,大家这些脱了裤子是人,穿上裤子是鬼的臭男人..") 7 break
回到上面for 循环的例子,如何实现让用户不断的猜年龄,但只给最多3次机会,再猜不对就退出程序。
1 #!/usr/bin/env python 2 # -*- coding: utf-8 -*- 3 4 5 my_age = 28 6 7 count = 0 8 while count < 3: 9 user_input = int(input("input your guess num:")) 10 11 if user_input == my_age: 12 print("Congratulations, you got it !") 13 break 14 elif user_input < my_age: 15 print("Oops,think bigger!") 16 else: 17 print("think smaller!") 18 count += 1 #每次loop 计数器+1 19 else: 20 print("猜这么屡次都不对,你个笨蛋.")