Python Cheat Sheet Codecademy



Python Cheat Sheet Codecademy

  1. Python Cheat Sheet Pdf
  • Python 3 Beginner's Reference Cheat Sheet Special characters # comentand n new lineor scape char dict.get Numeric operators + addition - subtraction. multiplication / division. exponent% modulus // floor division Boolean operators equal!= different higher = higher or equal.
  • Python allows the values in a dictionary to be any type – string, integer, a list, another dictionary, boolean, etc. However, keys must always be an immutable data type, such as strings, numbers, or tuples. In the example code block, you can see that the keys are strings or numbers (int or float). The values, on the other hand, are many varied data types.

A slice, or sub-list of Python list elements can be selected from a list using a colon-separated starting and ending point. The syntax pattern is myListSTARTNUMBER:ENDNUMBER.The slice will include the STARTNUMBER index, and everything until but excluding the ENDNUMBER item. When slicing a list, a new list is returned, so if the slice is saved and then altered, the original list remains.

Pdf

教程 code codecademy python

  1. name = raw_input(“What is your name”) # 获取用户输入
  2. 逻辑运算符: not, and, or
  3. list中:append多用于把元素作为一个整体插入;insert多用于固定位置插入;extend多用于list中多项分别插入;remove删除第一个匹配的元素;del根据index删除,返回删除后的list;pop也是index,但是返回的是删除的元素
  4. ”-“.join(list) # 在list中的元素间 添加-连接起来
  5. while/else, for/else: 循环正常退出(无break),else会执行
  6. print char, “,”保证输出不换行
  7. for index, item in enumerate(choices): # 同时获取index和item
  8. zip能创建2个以上lists的pair/tuple等,在最短的list的end处停止。
  9. a, b = 1, 2; a, b = str.split(‘-‘) # 逗号分别赋值
  10. print a, b 等同 print a + “ “ + b,但后者使用了字符串连接符,可能类型不匹配,前者更好
  11. lists[::-1],代表lists逆序
  12. [i for i in my if i%30] 等同 filter(lambda i: i%30, my) # 重组list列表
  13. with语句:如果对象包括方法__enter__()和__exit__(),则可以用,进行自动关闭文件;线程锁的自动获取和释放;异常的捕捉和打印;
  14. 类的没有参数的方法,是静态方法,属于这个类;实例对象的调用,需要有个self参数,a.func()–>func(a)
  15. if namemain’: 如果直接执行,为True;如果被其他module import,为False
  16. 重载运算符:add(self,other), mul, gt(self,other), lt, ge, le, pos(self), int(self,类型转换)
  17. str(self)定义当str()调用的时候的返回值,如print a;repr(self)定义repr()被调用的时候的返回值,如a
  1. iter(self)函数,会返回一个迭代器
    • 使用yield: 带有yield的函数在Python中被称之为generator:生成器
    • 函数内部用for循环包含yield语句,执行到yield var时,函数就返回一个迭代值var,下次迭代时,代码从yield var 的下一条语句继续执行,而函数的本地变量看起来和上次中断执行前是完全一样的,于是函数继续执行,直到再次遇到yield
  2. python是动态语言,比如一个类,可以在运行过程中随时添加属性
Python Cheat Sheet Codecademy

slots()可以用来限制该class能添加的属性

  1. 正则表达式re

Python Cheat Sheet Pdf

  1. 全局/局部变量
    • 函数内部的变量名如果第一次出现,且出现在=前面,即被视为定义一个局部变量
    • 函数内部的变量名如果第一次出现,且出现在=后边,则视为引用全局的变量
    • 函数内部如果想把全局变量,放到=前边赋值,需要加global修饰
    • file1.py的global_var,在file2.py中,需要import file1, file1.global_var这样用