<Python learning>Basic

来源:互联网 发布:程序员真的每天很累吗 编辑:程序博客网 时间:2024/06/14 21:41

Learn from Codecademy: https://www.codecademy.com/learn/python
& 廖雪峰 Python 教程

  1. Python 语法
  2. 字符串和控制台输出
  3. 条件和控制流
  4. 函数
  5. 列表和字典

List:

  1. 从列表当中移除某元素,3种方法:

    • n.pop(index) will remove the item at index from the list and return the removed element to you
    • n.remove(item) will remove the actual item(the element)
    • del(n[1]) is like .pop in that it will remove the item at the given index, but it won’t return the element
  2. Iterating over a list, 两种方法:

for item in list:    print item
for i in range(len(list)):    print list[i]
  1. 字符串’xxx’或Unicode字符串u’xxx’也可以看成是一种list,每个元素就是一个字符。因此,字符串也可以用切片操作,只是操作结果仍是字符串

Loop:

  1. While / else:
    while/elseif/else 很相似, 不同点在于:
    else 当中的内容,只有在循环条件(loop condition)为False 的时候才执行。也即是说,如果这个循环通过 break 退出了, 那么else 也不会执行

  2. For / else
    while/else一样,只有在 for 正常退出(循环完成)的时候才会执行,若是break 退出,则不执行

The , character after print statement means that next print statement keeps printing on the same line.

zip can help iterate over two lists at once. It will create pairs of elements when passed two or more lists, and will stop at the end of the shorter list.


Filter and Lambda Syntax

Lambda functions are defined using the following syntax:

my_list = range(16)filter(lambda x: x % 3 == 0, my_list)

Lambdas are useful when you need a quick function to do some work for you.

If you plan on creating a function you’ll use over and over, you’re better off using def and giving that function a name.

In Python, you can write numbers in binary format by starting the number with 0b.


Class Syntax

  • By convention, user-defined Python class names start with a capital letter.
  • Define an initial function using: init() (ou can think of init() as the method that “boots up” a class’ instance object. 记住是两个下划线…不是一个,一般第一个参数是self,表明是instance本身)
  • We can access attributes of our objects using dot notation
  • When a class has its own functions, those functions are called methods.
  • self 在function中也要作为参数写上
  • 关于继承函数:
class Derived(Base):   def m(self):       return super(Derived, self).m()

File Input/Output

my_list = [i**2 for i in range(1,11)]my_file = open("output.txt", "r+")#write things into the filefor i in my_list:    my_file.write(str(i)+"\n")#Always remember to close the file#If you write to a file without closing, the data won't make it to the target file.my_file.close()
  • read from a file line by line:.readline()

  • when a file object’s __exit__() method is invoked, it automatically closes the file. Use with and as to invoke:

with open("text.txt", "w") as textfile:    textfile.write("Success!")
  • Check if a file is closed or not: it will return False if not closed
f.closed