从今天起开始记录我的Python学习之路。

现在的我只是一个学习Linux服务器的大三学生党,在大学中不断的学习是必要的,学习完了写技术博客也是必要的,不管有没有人看,这对于自己来说都是有好处的。

最近发现Python这个强大的语言,就如它的名字一样,Python是一门强壮又迅捷的语言,所以引发了我对于它浓厚的兴趣。

鄙人一直认为,只要学好了C语言,再学其他语言真的是太容易了,所以我的学习之路一直都有C的伴随。今天有些晚了,先贴出今天看书写的第一个Python程序吧,这是一个猜随机数字的小程序,第一天就先这样吧

  1. #!/usr/bin/python 
  2. import random 
  3.  
  4. def checkNum(a,b): 
  5.         if a==b: 
  6.              print "yes!" 
  7.              return 1 
  8.         elif b>a: 
  9.              print "b>a" 
  10.         else
  11.              print "b<a" 
  12.  
  13. num=random.randrange(0,20
  14.  
  15. while True
  16.          try
  17.                  inNum=int(raw_input('please input:')) 
  18.                  if checkNum(num,inNum)==1
  19.                          break 
  20.          except ValueError: 
  21.                  print 'input error' 


<---------------------------我是华丽的日期分隔线------------------------------>
 
今天开始细看Python的一些基础,说道基础当然是从数据类型开始看起啦

看数据类型前,先看到了一个数字运算的例子:
  1. >>> 1/2 
  2. 0 
  3. >>> 1//2 
  4. 0 
  5. >>> 1.0/2 
  6. 0.5 
  7. >>> from __future__ import division 
  8. >>> 1/2 
  9. 0.5 
感觉Python里的数学运算变得so easy了,模块化的使用真的很方便啊。
再往下看看,除了长整型外还是没看到有说数据类型啊,对了,Python是弱类型啊。

abs()取绝对值,round()用来四舍五入,这些函数还是和其他语言差不多的。
  1. >>> abs(-19
  2. 19 
  3. >>> round(1/2
  4. 1.0 
不过Python中最强大的还是各种各样的模块,比如math模块中就有各种各样的数学函数可以调用。
下面两种import的方法我个人比较喜欢第一种,毕竟毕竟清晰嘛
  1. >>> import math 
  2. >>> math.floor(23.2
  3. 23.0 
  4. >>> int(math.floor(23.2)) 
  5. 23 
  6. >>> from math import sqrt 
  7. >>> sqrt(9
  8. 3.0 
最强大的来了,Python竟然可以计算出虚数啊
  1. >>> import cmath 
  2. >>> cmath.sqrt(-2
  3. 1.4142135623730951j 
  4. >>> (2+5j)*(9+2j
  5. (8+49j

<---------------------------我是华丽的日期分隔线------------------------------>
在Python中字符串的拼接是如此的简单
  1. >>> "hello,"+"world" 
  2. 'hello,world' 
  3. >>> x = "hello," 
  4. >>> y = "world!" 
  5. >>> x + y 
  6. 'hello,world!' 

 反撇号的用途是很明显的,但是据说``已经被repr()给代替了,所以还是用repr()吧,repr()则让数值得到解释

  1. >>> num = 25 
  2. >>> print "The num is " + num 
  3. Traceback (most recent call last): 
  4.   File "<stdin>", line 1in <module> 
  5. TypeError: cannot concatenate 'str' and 'int' objects 
  6. >>> print "The num is " + `num` 
  7. The num is 25 
  8. >>> print "The num is " + repr(num) 
  9. The num is 25 
  10. >>> str = "hello"
  11. >>> print "The string is " + str
  12. The string is hello
Unicode字符串的定义和普通ASCII字符串的定义
  1. >>> print u"hello , world!" 
  2. hello , world! 
  3. >>> print r"hello , world!" 
  4. hello , world! 

这是目前为止已经学习了的函数

我的Python学习之路_自学Python

 下面就要开始学习Python的数据结构啦,列表和元组。

这是一种类似字典的结构:

  1. >>> tom = [01,"teacher"
  2. >>> jerry = [02,"student"
  3. >>> index = [tom,jerry] 
  4. >>> print index 
  5. [[1'teacher'], [2'student']] 

这样看起来就是一个多维数组嘛

  1. >>> print index[1
  2. [2'student'
  3. >>> print index[0
  4. [1'teacher'
  5. >>> print index[0][1
  6. teacher 
  7. >>> print index[0][0
  8. 1

很神奇的一点是,Python可以用负数下标来取元素

  1. >>> test = "apple" 
  2. >>> test[1
  3. 'p' 
  4. >>> test[0
  5. 'a' 
  6. >>> test[-1
  7. 'e' 
  8. >>> test[-2
  9. 'l' 
  10. >>> test[-5
  11. 'a' 

在输入的字符中你也可以取你感兴趣的那个

  1. >>> month = raw_input('Y-M-D:')[4
  2. Y-M-D:20140420 
  3. >>> month 
  4. '0' 
那么来看一个具体的小程序吧
  1. #!/usr/bin/python 
  2. months = [ 
  3.         'January'
  4.         'February'
  5.         'March'
  6.         'April'
  7.         'May'
  8.         'June'
  9.         'July'
  10.         'August'
  11.         'September'
  12.         'Oxtober'
  13.         'November'
  14.         'December' 
  15.  
  16. endings = ['st','nd','rd'] + 17 * ['th'] \ 
  17.         + ['st','nd','rd'] + 7 * ['th'] \ 
  18.         + ['st'
  19.  
  20. year = raw_input('Year:'
  21. month = raw_input('Month(1-12):'
  22. day = raw_input('Day(1-31):'
  23.  
  24. month_number = int(month) 
  25. day_number = int(day) 
  26.  
  27. month_name = months[month_number-1
  28. ordinal = day + endings[day_number-1
  29.  
  30. print month_name + ' ' + ordinal + '. ' + year 
  31.  
  32. 运行结果: 
  33. [root@server py]# ./yearPrint.py  
  34. Year:2012 
  35. Month(1-12):12 
  36. Day(1-31):21 
  37. December 21st2012 
先前说了Python可以用负数当数组下标,这里再来看看分片的操作吧
  1. >>> url = 'http://www.baidu.com/index.html' 
  2. >>> url[7:20
  3. 'www.baidu.com' 
  4. >>> url[21:-1
  5. 'index.htm' 
  6. >>> num = [1,2,3,4,5
  7. >>> num[0:4
  8. [1234
  9. >>> num[2:]
  10. [3, 4, 5]
  11. >>> num[:4]
  12. [1, 2, 3, 4]
分片的操作还可以接步长,这使得对数组的操作变得更加的灵活可变了,比如说数组的逆序打印变得如此简单。 步长是不能为0的,不然就不能执行下去了。 基本语法: array[起始下标:结束下标:步长]
  1. >>> num = [1,2,3,4,5,6,7,8,9,10
  2. >>> num[0:10:2
  3. [13579
  4. >>> num[3:6:3
  5. [4
  6. >>> num[0:6:3
  7. [14
  8. >>> num[2::3
  9. [369
  10. >>> num[1::3
  11. [258
  12. >>> num[1:6:3
  13. [25
  14. >>> num[3:6:3
  15. [4
  16. >>> num[3:7:3
  17. [47
  18. >>> num[::-1
  19. [10987654321
看看上面这些例子,这些对数组的操作是多么的方便啊。 再用一个例子来说明一下分片的操作吧: 
  1. #!/usr/bin/python 
  2.  
  3. url = raw_input('Please enter the URL:'
  4.  
  5. isD = url[-3
  6. if isD=="."
  7.         domain = url[11:-3
  8. else
  9.         domain = url[11:-4
  10. print "Domain name:" + domain 
  11.  
  12. 运行结果: 
  13. [root@server py]# ./urlPrint.py  
  14. Please enter the URL:http://www.baidu.com 
  15. Domain name:baidu 
  16. [root@server py]# ./urlPrint.py  
  17. Please enter the URL:http://www.baidu.cn 
  18. Domain name:baidu 
序列的相加就如字符串的相加一样是将两个序列拼接在一起的:
  1. >>> num = [1,2,3,4,5,6,7,8,9,10
  2. >>> num2 = [11,12,0
  3. >>> num + num2 
  4. [1234567891011120
所以从根本上来看,很多操作序列和字符串都是相似的:
  1. >>> a = [1,2,3
  2. >>> a * 2 
  3. [123123
  4. >>> b = 'string' 
  5. >>> b * 2 
  6. 'stringstring' 
  7.  
空列表的初始化可以使用array = []来表示,但是如果想要看到列表中是10个空的呢? 那就用None吧,它Python的内建值,表示什么都没有。

  1. >>> c = [] 
  2. >>> c 
  3. [] 
  4. >>> d = [None]*10 
  5. >>> d 
  6. [NoneNoneNoneNoneNoneNoneNoneNoneNoneNone

 <---------------------------我是华丽的日期分隔线------------------------------> 

今天早上起来就在想怎么才能读取文件中的某几行某几列的数据放到数组中呢,在网上找了一下发现就是用昨天学习的序列就可以实现了,真的是物以致用啊。

  1. #!/usr/bin/python 
  2. import random 
  3. file = open("file","r"
  4. content = [x.rstrip("\n"for x in file] 
  5. file.close 
  6.  
  7. data = [x.split()[1:2for x in content[:]] 
  8. #如果你的数据不是以字符列为界,而是以空格分隔,加上split()  
  9. #这个是取单个字符:data = [x[3:] for x in content[2:]]  
  10. print data 
  11. a=random.randrange(0,len(data)) 
  12. i=0 
  13. while i<len(data): 
  14.         print data[i] 
  15.         i=i+1 
  16. print "singer is " + data[a][0

 检查一个值是否存在序列中可以用in来检测,它会返回True或False。

  1. >>> user = ['tom','jerry']  
  2. >>> raw_input('Enter your user name:'in user  
  3. Enter your user name:tom  
  4. True  
  5. >>> id = [1,2,3,4,5]  
  6. >>> 1 in id  
  7. True  
  8. >>> 11 in id  
  9. False  
  10. >>> database = [['tom','123'],['jerry','123']] 
  11. >>> username = raw_input('Enter your user name:'
  12. Enter your user name:tom 
  13. >>> password = raw_input('Enter password:'
  14. Enter password:123 
  15. >>> if [username,password] in database:print 'ok!' 
  16. ...  
  17. ok! 

内建函数len()、min()、max()非常有用

len()返回序列中包含元素的数量

min()和max()分别返回序列中最大和最小的元素

  1. >>> test = ['abc','abcd','ab','abcde','a'
  2. >>> max(test) 
  3. 'abcde' 
  4. >>> min(test) 
  5. 'a' 
  6. >>> len(test) 
  7. 5 
  8. >>> i = [1,20,100,999
  9. >>> min(i) 
  10. 1 
  11. >>> max(i) 
  12. 999 
  13. >>> len(i) 
  14. 4 

列表是非常有用的,所以也有人说列表是Python的苦力~

列表是可变的,而字符串是不可变的,所以用list()函数可以实现字符串转换成列表。

  1. >>> list('hello'
  2. ['h''e''l''l''o'
  3. >>> hello = list('hello'
  4. >>> del hello[3
  5. >>> hello 
  6. ['h''e''l''o'
  7. >>> hello[2]='r' 
  8. >>> hello 
  9. ['h''e''r''o'

在这里我们可以再来用用之前的分片操作

array[i:]=list('str')表示在array列表的2号元素开始替换为'str'

  1. >>> hello = list('hello')   
  2. >>> hello   
  3. ['h''e''l''l''o']   
  4. >>> hello[2:]=list('ad')   
  5. >>> hello   
  6. ['h''e''a''d']   
  7. #在此可以看出,本来的4号元素没有进行替换而是直接消失了   
  8. >>> hello[1:2]=list('i')  
  9. >>> hello  
  10. ['h''i''a''d']  
  11. #而在这里,却只替换了1号元素,后面的没有影响,这就是分片的神奇之处呐!  
  12. >>> hello = list('python'
  13. >>> hello 
  14. ['p''y''t''h''o''n'
  15. >>> hello[1:5]=[] 
  16. >>> hello 
  17. ['p''n'
  18. #在这里是将从1号元素开始直到5号元素前,替换为空,就是删除啦~ 
  19. >>> hello[1:1]=list('ytho'
  20. >>> hello 
  21. ['p''y''t''h''o''n'
  22. #这里是从1号元素开始又到1号元素之前替换为列表list('ytho'),这是哪里?这就是在0号元素后插入列表list('ytho')啦~ 

注意Python内建函数名一定不能被一定为变量名,不然的话函数就不能用了哦!

在来看看加了步长后的序列会怎么样呢?

  1. >>> hello 
  2. ['a''a''n'
  3. >>> hello[:0]=list('b'
  4. >>> hello 
  5. #这里终止为0就是在最前面插入列表哦 
  6. ['b''a''a''n'
  7. >>> hello[:]=list('c'
  8. >>> hello 
  9. ['c'
  10. #这里什么都不指定的话,就是整个替换了 
  11. >>> hello 
  12. ['d''d''n'
  13. >>> hello[:-1]=list('a'
  14. >>> hello 
  15. ['a''n'
  16. #终止处-1就使得替逆序了,同样前面的字符也被空给覆盖了 
  17. >>> hello 
  18. ['a''a''a'
  19. >>> hello[:1:-1]=list('c'
  20. >>> hello 
  21. ['a''a''c'
  22. #这里指定了终止处为1号元素处,步长为-1,所以只有最后一个元素符合标准所以替换了,事实上如果有两个或两个以上的匹配会报错的~ 

 <---------------------------我是华丽的日期分隔线------------------------------>

接下来我们来看看列表对象的一些方法吧

1.append方法:用于在列表末尾追加新对象

  1. >>> lst = [1,2,3
  2. >>> lst.append(4
  3. >>> lst 
  4. [1234

2.count方法:统计某个元素在列表中出现的次数

  1. >>> string 
  2. ['a''ab''abc''abcd''abcde''a'
  3. >>> string.count('a'
  4. 2 

3.extend方法:可以在列表末尾一次追加多个新对象,当然也可以用分片实现

  1. >>> a = [1,2,3
  2. >>> b = [4,5,6
  3. >>> a.extend(b) 
  4. >>> a 
  5. [123456
  6. #用分片实现
  7. >>> a
  8. [1, 2, 3, 4, 5, 6]
  9. >>> b
  10. [4, 5, 6]
  11. >>> a[len(a):] = b
  12. >>> a
  13. [1, 2, 3, 4, 5, 6, 4, 5, 6]

4.index方法:用于找出列表中某个值第一次出现在列表中的索引位置

  1. >>> string 
  2. ['a''ab''abc''abcd''abcde''a'
  3. >>> string.index('a'
  4. 0 
  5. >>> string.index('ab'
  6. 1 

5.insert方法:用于将对象插入列表中

  1. >>> a 
  2. [123456456
  3. >>> a.insert(0,'zero'
  4. >>> a 
  5. ['zero'123456456

6.pop方法:移除列表的一个元素,返回它的值。append和pop可以实现进栈出栈

  1. >>> num 
  2. [1613532
  3. >>> num.pop() 
  4. 2 
  5. >>> num 
  6. [161353
  7. >>> num.pop(1
  8. 13 

7.remove方法:用于移除列表中找到的第一个匹配项

  1. >>> a 
  2. ['zero'123456456
  3. >>> a.remove(4
  4. >>> a 
  5. ['zero'12356456

 

8.reverse方法:用于将列表中的元素反向存放

  1. >>> a 
  2. ['zero'12356456
  3. >>> a.reverse() 
  4. >>> a 
  5. [65465321'zero'

9.sort方法:用于将列表中的元素排序直接存入序列

  1. >>> num = [ 3,5,2,16,13
  2. >>> num 
  3. [3521613
  4. >>> num.sort(cmp) 
  5. >>> num 
  6. [2351316
  7. >>> num.sort(cmp,reverse=True
  8. >>> num 
  9. [1613532
  10. >>> string = ['abc','abcd','a','ab','abcde'
  11. >>> string.sort(reverse=True
  12. >>> string 
  13. ['abcde''abcd''abc''ab''a'
  14. >>> string.sort(cmp,reverse=True)  #逆序 
  15. >>> string 
  16. ['abcde''abcd''abc''ab''a'
  17. >>> string.sort(cmp)     #cmp用于比较大小 
  18. >>> string 
  19. ['a''ab''abc''abcd''abcde'
  20. >>> string.sort(key=len) #根据长度排序 
  21. >>> string 
  22. ['a''ab''abc''abcd''abcde'