Python 快速入门

0.引言
不知道在哪里看到过,一个优秀的程序员应该一年学习一种新语言。我觉得很有道理。学习新语言的好处很多,首先就是开阔眼界,了解不同语言的特性和思想;多懂一种语言多一个方便,能看懂更多别人的代码,需要的时候也给自己多一个选择;最后一点也是最重要的一点,保持自己旺盛自己学习能力,不要在工作中整天就接触一些狭隘的东西,改无聊的bug,让自己萎靡下去。 
本文适合同有其他语言基础但Python基础为零的人分享。
1. 安装
Python 在Unix-like的系统上是标准配置,不需要安装,在Windows上只要去www.python.org上下载一个安装文件即可 Python可以在命令行下面交互执行,很方便。安装完毕后可以在命令行下检查下版本号,
yin@UnixCenter:~$ python -V
Python 2.5.2
本人的计算机上是Ubuntu 8.04上标配的Python,目前最新版已经是3.1。不过本系列文章的内容基本不会超过Python 2.5的内容。
2.Python核心类型简介
Python是弱类型的语言,不过其内部还是有一些基本类型的,主要有 Number,String,List,Dictionary,Tuple,Files,Sets,types,None,Boolean. 这些类型基本在其他编程语言里边也有,有几个比较特殊,比如Tuple,表示一个四元组,用的也不是太多,以后再说。其他的都很熟悉,尤其和Javascript很像。下面举几个例子说明如何使用这些类型:
yin@UnixCenter:~$ python
Python 2.5.2 (r252:60911, Jul 22 2009, 15:35:03) 
[GCC 4.2.4 (Ubuntu 4.2.4-1ubuntu3)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> d=100;
>>> c=152;
>>> d+c
252
>>> s='hello python';
>>> k=' I love you';
>>> s+k;
'hello python I love you'
>>> s[-1]+s[1]
'ne'
>>> list=[1,2,[3,4,5,'ok'],6];
>>> list[0]+list[1]+list[2][2]
8
>>> dic={'hello':'python','hi':['java']};
>>> dic['hello']
'python'
>>> dic['hi'].append('C++');
>>> dic['hi']
['java', 'C++']
>>> dic['hi']+['C#','vb'];
['java', 'C++', 'C#', 'vb']
>>> len(dic)
2
注意最后List的长度,执行了相加后是得到一个新的list,而原来的list并不会改变。
>>> d='100';
>>> d+90
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: cannot concatenate 'str' and 'int' objects
注意,不同类型的变量不能直接相加。
>>> dir(dic)
['__class__', '__cmp__', '__contains__', '__delattr__', '__delitem__', '__doc__', '__eq__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__str__', 'clear', 'copy', 'fromkeys', 'get', 'has_key', 'items', 'iteritems', 'iterkeys', 'itervalues', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values']
可以用dir函数查看一个对象所拥有的方法。
Python把文件也作为基本类型之一,操作文件非常方便。
>>> f=open('test.txt','w');
>>> f.write('hello \n python \n');
>>> f.close();
>>> r=open('test.txt','r');
>>> b=r.read();
>>> print b;
hello 
 python 
3. 数字类型
Python支持多种数字类型,包括整数(不限长度),浮点数(实现为C的double),16进制和8进制的数字表示法,以及复数。
Python的运算符基本和C是类似的,有几个不同:
x if y else z, 例如:>>> 'a' if 3>4 else 'b'; 结果是b
逻辑运算符:x or y, x and y, not x
集合判断: x in y
直接支持复数的语言是很少的,不过Python支持:
>>> (2+4j)*(1-5j)
(22-6j)
4.基本语法
要注意,Pyhton的语句块不是通过常见的{}或者begin,end,而是严格的通过缩进来判断的。因此说Python的设计就十分注重可阅读性。
4.1 while循环
while <expression>:
缩进语句块
例: 编写文件while.py如下:
reply="";
while reply!="stop":
    reply=raw_input("Enter Text:");
    print reply
print "You stopped the program..."
运行结果:
yin@UnixCenter:~/Documents/python$ python while.py
Enter Text:sdf
sdf
Enter Text:stop
stop
You stopped the program...
4.2 if语句
if <expression>:
    缩进语句块
[elif <expression>:
    缩进语句块
]
[else:
   缩进语句块]
例:
x=13;
if x>0 and x<10:
    print 'Class A';
elif x>=10 and x<20:
    print 'Class B';
else:
    print 'Class C';
运行结果:
yin@UnixCenter:~/Documents/python$ python if.py
Class B
最后写一个经典的综合性小例子,计算孪生素数,也就是两个连续奇数,他们都是素数。孪生素数是不是存在无穷多对,现在仍是一个未解之谜。
prime.py:
stop=10000000;
current=3;
primeFind=[2];
pairCount=0;    
while current<stop:
    isPrime=True;
    for p in primeFind:
        if(current%p==0):
            isPrime=False;
            break;
    if isPrime:
        primeFind.append(current);
        if current-primeFind[-2]==2:
            pairCount+=1;
            print "The %dth Paired Prime is: %d and %d"% (pairCount,primeFind[-2],current);
    current+=2;
区区16行,Python果然是很优雅的语言...
最后的运行结果自然是无穷无尽,我贴出我运行到的最后三条吧(大约跑了半个小时):
The 9999th Paired Prime is: 1260899 and 1260901
The 10000th Paired Prime is: 1260989 and 1260991
The 10001th Paired Prime is: 1261079 and 1261081
呵呵,平均每100个自然数就有1对哦...质数们还是蛮亲密的嘛! 当然,数字越大比例会越来越小...
posted @ 2011-03-20 16:14  yinzixin  阅读(736)  评论(0编辑  收藏  举报