您的位置:首页 > 编程语言 > Python开发

[带你飞]一小时带你学会Python

2015-01-23 17:09 363 查看
1.面向的读者:

具有Javascript经验的程序猿。

2 快速入门
2.1 Hello world

安装完Python之后,打开IDLE(Python GUI) , 该程序是Python语言解释器,你写的语句能够立即运行.我们写下一句著名的程序语句:

print "Hello,world!"


并按回车.你就能看到这句被K&R引入到程序世界的名言.

在解释器中选择"File"--"New Window" 或快捷键 Ctrl+N , 打开一个新的编辑器.写下如下语句:

print "Hello,world!"
raw_input("Press enter key to close this window...");


保存为a.py文件.按F5,你就可以看到程序的运行结果了.这是Python的第二种运行方式.

找到你保存的a.py文件,双击.也可以看到程序结果.Python的程序能够直接运行,对比Java,这是一个优势.

2.2 国际化支持
我们换一种方式来问候世界.新建一个编辑器并写如下代码:

print "欢迎来到奥运中国!"
raw_input("Press enter key to close this window...");


在你保存代码的时候,Python会提示你是否改变文件的字符集,结果如下:

# -*- coding: cp936 -*-

print "欢迎来到奥运中国!"
raw_input("Press enter key to close this window...");


将该字符集改为我们更熟悉的形式:

# -*- coding: GBK -*-

print "欢迎来到奥运中国!" # 使用中文的例子
raw_input("Press enter key to close this window...");


程序一样运行良好.

2.3 方便易用的计算器
用微软附带的计算器来计数实在太麻烦了.打开Python解释器,直接进行计算:

a=100.0
b=201.1
c=2343
print (a+b+c)/c


Python会自动帮你实现类型转换。

2.4 字符串,ASCII和UNICODE
可以如下打印出预定义输出格式的字符串:

print """
Usage: Python
-Java
-C++
"""


结果输出:

Usage: Python
-Java
-C++


字符串是怎么访问的?请看这个例子:

word="abcdefg"                         // 数组
a=word[2]                              // 数组中的一个值
print "a is: "+a
b=word[1:3]                            // 数组范围,取1到2的值,但是不取最后区间的值
print "b is: "+b # index 1 and 2 elements of word.
c=word[:2]                             // 数组范围,从开始取到2,但是不取2的值
print "c is: "+c # index 0 and 1 elements of word.
d=word[0:]                             // 从头开始取到尾
print "d is: "+d # All elements of word.
e=word[:2]+word[2:]                    // 继续从头取到尾
print "e is: "+e # All elements of word.
f=word[-1]                             // 取最后一个元素“g”
print "f is: "+f # The last elements of word.
g=word[-4:-2]                          // 倒着取,打印“de”
print "g is: "+g # index 3 and 4 elements of word.
h=word[-2:]                            // 倒着取,打印“fg”
print "h is: "+h # The last two elements.
i=word[:-2]                            // 倒着去,打印“abcde”
print "i is: "+i # Everything except the last two characters
l=len(word)                            // 长度,结果为7
print "Length of word is: "+ str(l)


请注意ASCII和UNICODE字符串的区别:

print "Input your Chinese name:"
s=raw_input("Press enter to be continued...");
print "Your name is ... : " +s;
l=len(s)
print "Length of your Chinese name in asc codes is:"+str(l);
a=unicode(s,"GBK")
l=len(a)
print "I'm sorry we should use unicode char!Characters number of your Chinese \
name in unicode is:"+str(l);


2.5 使用List
类似Java里的List,这是一种方便易用的数据类型:

word=['a','b','c','d','e','f','g']
a=word[2]                                                 // a is: c
print "a is: "+a
b=word[1:3]
print "b is: "
print b # index 1 and 2 elements of word.                 // ['b', 'c']
c=word[:2]
print "c is: "
print c # index 0 and 1 elements of word.                 // ['a', 'b']
d=word[0:]
print "d is: "
print d # All elements of word.                           // ['a', 'b', 'c', 'd', 'e', 'f', 'g']
e=word[:2]+word[2:]
print "e is: "
print e # All elements of word.                           // ['a', 'b', 'c', 'd', 'e', 'f', 'g']
f=word[-1]
print "f is: "
print f # The last elements of word.                      // g
g=word[-4:-2]
print "g is: "
print g # index 3 and 4 elements of word.                 // ['d', 'e']
h=word[-2:]
print "h is: "
print h # The last two elements.                          // ['f', 'g']
i=word[:-2]
print "i is: "
print i # Everything except the last two characters       // ['a', 'b', 'c', 'd', 'e']
l=len(word)
print "Length of word is: "+ str(l)                       // 7
print "Adds new element..."
word.append('h')
print word                                                // ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']


2.6 条件和循环语句

# Multi-way decision
x=int(raw_input("Please enter an integer:"))
if x>0:
print "x>0"
elif x==0:
print "Zero"
else:
print "x<0"


while循环:

x=0
while (x<10):
print 'x is:', x     // 需要特别注意的是:这里一定要缩进,不然会编译不过
x+=1

print "end!"


for循环

words=['this','is','a','A']
for word in words:
print word


提示:能使用for循环,就尽量不使用while循环

2.7 如何定义函数

def hello(name):
return 'hello ' + name + '!'

print hello('a')


并且,介绍一个方便好用的函数:

函数原型:range(start, end, scan):

参数含义:start:计数从start开始。默认是从0开始。例如range(5)等价于range(0, 5);

end:技术到end结束,但不包括end.例如:range(0, 5) 是[0, 1, 2, 3, 4]没有5

scan:每次跳跃的间距,默认为1。例如:range(0, 5) 等价于 range(0, 5, 1)

>>> range(0, 8)
[0, 1, 2, 3, 4, 5, 6, 7]
>>> range(-5, -2)
[-5, -4, -3]
>>> range(-2, -5)
[]
>>> range(0, 6, 2)
[0, 2, 4]


我们再来试试麻烦的递归函数

def foo(i):
print 'the number is: ', i
i+=1
if i<10:
foo(i)
else:
print 'end!'

foo(0)


打印:

>>>
the number is:  0
the number is:  1
the number is:  2
the number is:  3
the number is:  4
the number is:  5
the number is:  6
the number is:  7
the number is:  8
the number is:  9
end!


2.8 文件I/O

spath="F:/1.txt"
f=open(spath,"w") # Opens file for writing.Creates this file doesn't exist.
f.write("First line 1.\n")
f.writelines("First line 2.")
f.close()                                   // 1.txt 会被写入上面两行

f=open(spath,"r") # Opens file for reading

for line in f:
print line

f.close()


2.9 异常处理

s=raw_input("Input your age:")
if s =="":
raise Exception("Input must no be empty.")
try:
i=int(s)
except ValueError:
print "Could not convert data to an integer."
except:
print "Unknown exception!"

else: # It is useful for code that must be executed if the try clause does not raise an exception
print "You are ",s, "years old"

print "Goodbye!"


2.10 类和继承

先看类的定义:

_metaclass_ = type
class Person:
def setName(self, name):
self.name = name
def getName(self):
return self.name
def greet(self):
print "hello, world. i am  %s." % self.name

foo=Person()
bar=Person()
foo.setName('lucy')
bar.setName('lili')

foo.greet()
bar.greet()


为什么会有self呢?

在c++中,this指针是隐式的,除非不得以的时候,,比如传进来的参数和类的成员变量的名字相同,或者要返回当前对象。 而python的self是显示的。而且this指针基本上不用在函数头里面。
python是动态语言,设计出来的类和静态语言的格式不同,首先c++在类的定义(声明)时,会指定类的成员变量,比如在private:里。但是Python不行,它没法显式的说 哪个属性是自己的,而且属性还可以动态的增加,此时,一个解决方案出来了,增加self,通过self.访问的就可以做为类的属性。至于类的方法为什么要显式的写上self(我感觉,完全可以由解释器隐式添加上去),估计就是python的哲学导致的:Explicit is better than implicit.

接下里是继承:

在python中继承中的一些特点:
1:在继承中基类的构造(__init__()方法)不会被自动调用,它需要在其派生类的构造中亲自专门调用。
2:在调用基类的方法时,需要加上基类的类名前缀,且需要带上self参数变量。区别于在类中调用普通函数时并不需要带上self参数
3:Python总是首先查找对应类型的方法,如果它不能在派生类中找到对应的方法,它才开始到基类中逐个查找。(先在本类中查找调用的方法,找不到才去基类中找)。

# -*- coding: utf-8 -*-
_metaclass_ = type
class Fruit:
def __init__(self, color):
self.color = color
print "fruit's color: %s" % self.color

def grow(self):
print "grow..."

class Apple(Fruit):                               #继承了父类
def __init__(self, color):                  #显示调用父类的__init__方法
Fruit.__init__(self, color)
print "apple's color: %s" % self.color

class Banana(Fruit):                              #继承了父类
def __init__(self, color):                  #显示调用父类的__init__方法
Fruit.__init__(self, color)
print "banana's color:%s" % self.color

def grow(self):                             #覆盖了父类的grow方法
print "banana grow..."

if __name__ == "__main__":
apple = Apple("red")
apple.grow()
banana = Banana("yellow")
banana.grow()


结果显示:

>>>
fruit's color: red
apple's color: red
grow...
fruit's color: yellow
banana's color:yellow
banana grow...


2.11 包机制
每一个.py文件称为一个module,module之间可以互相导入.请参看以下例子:

# a.py
def add_func(a,b):
return a+b


# b.py
from a import add_func # Also can be : import aprint "Import add_func from module a"
print "Result of 1 plus 2 is: "
print add_func(1,2)    # If using "import a" , then here should be "a.add_func"


module可以定义在包里面。

Python定义包的方式稍微有点古怪,假设我们有一个parent文件夹,该文件夹有一个child子文件夹.child中有一个module a.py . 如何让Python知道这个文件层次结构?很简单,每个目录都放一个名为_init_.py 的文件.该文件内容可以为空.这个层次结构如下所示:

parent
--__init_.py
--child
-- __init_.py
--a.pyb.py


那么Python如何找到我们定义的module?在标准包sys中,path属性记录了Python的包路径.你可以将之打印出来:

import sys
print sys.path


通常我们可以将module的包路径放到环境变量PYTHONPATH中,该环境变量会自动添加到sys.path属性.另一种方便的方法是编程中直接指定我们的module路径到sys.path 中:

import sys
sys.path.append('D:\\download')from parent.child.a import add_func

print sys.path

print "Import add_func from module a"
print "Result of 1 plus 2 is: "
print add_func(1,2)


总结
你会发现这个教程相当的简单.许多Python特性在代码中以隐含方式提出,这些特性包括:Python不需要显式声明数据类型,关键字说明,字符串函数的解释等等.你能够通过已有知识的迁移类比尽快熟悉Python,然后尽快能用它开始编程.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: