Python Codecademy 学习笔记

前段时间在码农周刊上看到了一个不错的学习Python的网站(Code Cademy),不是枯燥的说教,而是类似于游戏世界中的任务系统,一个一个的去完成。一做起来就发现根本停不下来,历经10多个小时终于全部完成了,也相应的做了一些笔记。过段时间准备再做一遍,更新下笔记,并加深了解。

  1. name = raw_input("What is your name")
    这句会在console要求用户输入string,作为name的值。

  2. 逻辑运算符顺序:not>and>or

  3. dir(xx) : sets xx to a list of things

  4. list

a = []
a.insert(1,"dog") # 按顺序插入,原有顺序会依次后移
a.remove(xx)
  1. dict
    1. del dic_name['key']
    2. loop:
d = {"foo" : "bar"}
for key in d:
    print d[key]
 3) another way to find key: `print d.items()`
  1. print [“O”]*5 : [‘O’, ‘O’, ‘O’, ‘O’, ‘O’]

  2. join操作符:

     letters = ['a', 'b', 'c', 'd']
     print "---".join(letters)

输出为a---b---c---d

  1. while/else, for/else
    只要循环正常退出(没有碰到break什么的),else就会被执行。

  2. print 和 逗号

word = "Marble"
for char in word:
    print char,

这里“,”保证了输出都在同一行

  1. for循环中的index
choices = ['pizza', 'pasta', 'salad', 'nachos']
print 'Your choices are: '
for index, item in enumerate(choices):
    print index, item

enumerate可以帮我们为被循环对象创建index

  1. zip能创建2个以上lists的pair,在最短的list的end处停止。

  2. 善用逗号

a, b, c = 1, 2, 3
a, b, c = string.split(':')
  1. 善用逗号2
    print a, b 优于 print a + " " + b,因为后者使用了字符串连接符,可能会碰到类型不匹配的问题。

  2. List分片
    活用步长的-1:

lists = [1,2,3,4,5]; 
print lists[::-1]

输出结果:[5,4,3,2,1]

  1. filter 和 lambda
my_list = range(16)
print filter(lambda x: x % 3 == 0, my_list)

会把符合条件的值给留下,剩下的丢弃。打印出[0, 3, 6, 9, 12, 15]

  1. bit operation

    1. print 0b111 #7, 用二进制表示10进制数
    2. bin()函数,返回二进制数的string形式;类似的,oct(),hex()分别返回八进制和十六进制数的string。
    3. int("111",2),返回2进制111的10进制数。
  2. 类的继承和重载

    1. 可以在子类里直接定义和父类同名的方法,就自动重载了。
    2. 如果子类已经定义了和父类同名的方法,可以直接使用super来调用父类的方法,例如
class Derived(Base):
      def m(self):
      return super(Derived, self).m()
  1. File I/O
    1. f = open("a.txt", "w") : 这里w为write-only mode,还可以是r (read-only mode) 和 r+ (read and write mode),a (append mode)
    2. 写文件语法 f.write(something)。这里注意something一定要为string类型,可以用str()强制转换。不然会写入报错。
    3. 读全文件非常简单,直接f.read()就好。
    4. 如果要按行读文件,直接f.readline()会读取第一行,再调用一次会读取第二行,以此类推。
    5. 读或写完文件后,一定要记得f.close()
    6. 自动close file:
with open("text.txt", "w") as textfile:
        textfile.write("Success!")
`with`和`as`里有内嵌的方法`__enter__()`和`__exit__()`,会自动帮我们close file。
 7) 检查文件有没有被关闭,`f.closed`。
  1. List Comprehensions
    Python支持便捷的完成List的表达式,例如原代码:
list_origin = [1, 2, 3, 4, 5, 6]
list_new = []
for i in list_origin:
     if i % 2 == 0:
         list_new.append(i)

可以直接一行搞定:

list_origin = [1, 2, 3, 4, 5, 6]
list_new = [i for i in list_origin if i % 2 == 0]

Reference##

  1. Codecademy Python Program
    (http://www.codecademy.com/zh/tracks/python)
    原文作者:秦梦
    原文地址: https://www.jianshu.com/p/32b6c8237b97
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞