[toc]

## 语法(Syntax)

 1 2 3 4  if 5 > 2: print("Five is greater than two!") if 5 > 2: print("Five is greater than two!") 

### 注释(Comment)

 1 2 3 4 5 6  # Single Line Comment """ Multiple Line Comment """ 

## 变量(Variables)

 1 2  x = 5 y = "Hello, World!" 

 1 2 3  x = str(3) # x will be '3' y = int(3) # y will be 3 z = float(3) # z will be 3.0 

 1 2 3 4  x = 5 y = "John" print(type(x)) print(type(y)) 

 1 2 3 4  x, y, z = "Orange", "Banana", "Cherry" x = y = z = "Orange" fruits = ["apple", "banana", "cherry"] x, y, z = fruits 

 1 2 3 4  x = "awesome" def myfunc(): print("Python is " + x) myfunc() 

 1 2 3 4 5 6  x = "awesome" def myfunc(): x = "fantastic" print("Python is " + x) myfunc() print("Python is " + x) 

 1 2 3 4 5  def myfunc(): global x x = "fantastic" myfunc() print("Python is " + x) 

 1 2 3 4 5 6  x = "awesome" def myfunc(): global x x = "fantastic" myfunc() print("Python is " + x) 

### 数值(Number)

 1 2 3 4 5 6 7  x = 3+5j y = 5j z = -5j print(type(x)) print(type(y)) print(type(z)) 

### 真值(Boolean)

 1 2 3 4 5  x = "Hello" y = 15 print(bool(x)) print(bool(y)) 

## 条件与循环(If…Else/While/For)

 1 2 3 4 5 6 7 8  a = 200 b = 33 if b > a: print("b is greater than a") elif a == b: print("a and b are equal") else: print("a is greater than b") 

 1  if a > b: print("a is greater than b") 

 1 2 3 4  a = 2 b = 330 print("A") if a > b else print("B") print("A") if a > b else print("=") if a == b else print("B") 

 1 2 3 4 5 6 7  a = 200 b = 33 c = 500 if a > b and c > a: print("Both conditions are True") if a > b or a > c: print("At least one of the conditions is True") 

 1 2  if b > a: pass 

while 循环很常规：

 1 2 3 4 5 6 7 8  i = 1 while i < 6: print(i) if i == 3: break if i == 4: continue i += 1 

 1 2 3 4 5 6  i = 1 while i < 6: print(i) i += 1 else: print("i is no longer less than 6") 

 1 2 3 4 5  i = 1 while i < 6: break else: print("i is no longer less than 6") 

Python 中的 for 循环，更像是其他语言中的 foreach.

 1 2 3 4 5 6 7  fruits = ["apple", "banana", "cherry"] for x in fruits: if x == "apple": continue print(x) if x == "banana": break 

 1 2 3 4  for x in range(6): #generate an array containing 0,1,2,3,4,5 print(x) for x in range(2, 6): #[2,6) print(x) 

 1 2  for x in range(2, 30, 3): print(x) 

 1 2 3 4  for x in range(6): print(x) else: print("Finally finished!") 

 1 2  for x in [0, 1, 2]: pass 

## 字符串(String)

 1 2  print("Hello") print('Hello') 

 1 2 3 4 5  a = """Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.""" print(a) 

 1 2  a = "Hello, World!" print(a[0]) 

 1 2  a = "Hello, World!" print(len(a)) 

 1 2 3 4 5 6 7  txt = "The best things in life are free!" print("free" in txt) print("expensive" not in txt) if "free" in txt: print("Yes, 'free' is present.") if "expensive" not in txt: print("Yes, 'expensive' is NOT present.") 

• upper，大写。
• lower，小写。
• strip，去除两端空格。
• replace，替换。
• split，以特定分隔符分割。

 1 2 3 4  a = "Hello" b = "World" c = a + b print(c) 

 1 2 3 4 5  quantity = 3 itemno = 567 price = 49.95 myorder = "I want {} pieces of item {} for {} dollars." print(myorder.format(quantity, itemno, price)) 

 1 2  myorder = "I want to pay {2} dollars for {0} pieces of item {1}." print(myorder.format(quantity, itemno, price)) 

 1  txt = "We are the so-called \"Vikings\" from the north." 

## 操作符(Operators)

• 算术运算符
• +
• -
• *
• /
• %，取模。
• **，次幂，例如 2**10 返回 $1024$.
• //，向下取整，严格向下取整，例如 -11//10 将会得到 $-2$.
• 比较运算符
• ==
• !=
• >
• <
• >=
• <=
• 逻辑运算符，使用英文单词而非符号。
• and
• or
• not
• 身份运算符？(Identity Operators)
• is
• is not
• 用于判断是否为同一个对象，即在内存中处于相同的位置。
• 成员运算符？(Membership Operators)
• in
• not in
• 用在集合中。
• 位运算符
• &
• |
• ^
• ~
• <<
• >>

## 集合(Collections)

### 数组(List)

 1 2  thislist = ["apple", "banana", "cherry"] print(thislist) 

 1 2  thislist = ["apple", "banana", "cherry"] print(thislist[0]) 

 1 2  thislist = ["apple", "banana", "cherry"] print(thislist[-1]) 

 1 2  thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"] print(thislist[2:5]) 

 1 2 3  thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"] print(thislist[:4]) print(thislist[2:]) 

 1 2  thislist = ["apple", "banana", "cherry"] print(len(thislist)) 

 1  list1 = ["abc", 34, True, 40, "male"] 

 1 2  thislist = list(("apple", "banana", "cherry")) # note the double round-brackets print(thislist) 

 1 2 3  thislist = ["apple", "banana", "cherry"] thislist[1] = "blackcurrant" print(thislist) 

 1 2 3  thislist = ["apple", "banana", "cherry", "orange", "kiwi", "mango"] thislist[1:3] = ["blackcurrant", "watermelon"] print(thislist) 

 1 2 3  thislist = ["apple", "banana", "cherry"] thislist[1:2] = ["blackcurrant", "watermelon"] print(thislist) 

 1 2 3  thislist = ["apple", "banana", "cherry"] thislist.insert(2, "watermelon") print(thislist) 

 1 2 3  thislist = ["apple", "banana", "cherry"] thislist.append("orange") print(thislist) 

 1 2 3 4  thislist = ["apple", "banana", "cherry"] tropical = ["mango", "pineapple", "papaya"] thislist.extend(tropical) print(thislist) 

 1 2 3 4  thislist = ["apple", "banana", "cherry"] thistuple = ("kiwi", "orange") thislist.extend(thistuple) print(thislist) 

 1 2 3  thislist = ["apple", "banana", "cherry"] thislist.remove("banana") print(thislist) 

 1 2 3 4  thislist = ["apple", "banana", "cherry"] thislist.pop(1) thislist.pop() print(thislist) 

 1 2 3 4  thislist = ["apple", "banana", "cherry"] del thislist[0] print(thislist) del thislist #delete the entire list 

 1 2 3  thislist = ["apple", "banana", "cherry"] thislist.clear() print(thislist) 

 1 2 3  thislist = ["apple", "banana", "cherry"] for x in thislist: print(x) 

 1 2 3  thislist = ["apple", "banana", "cherry"] for i in range(len(thislist)): print(thislist[i]) 

 1 2 3 4 5  thislist = ["apple", "banana", "cherry"] i = 0 while i < len(thislist): print(thislist[i]) i = i + 1 

 1 2  thislist = ["apple", "banana", "cherry"] [print(x) for x in thislist] 

  1 2 3 4 5 6 7 8 9 10 11 12  fruits = ["apple", "banana", "cherry", "kiwi", "mango"] newlist = [] newlist = [x for x in fruits if "a" in x] #Equals to for x in fruits: if "a" in x: newlist.append(x) print(newlist) 

 1  newlist = [expression for item in iterable if condition == True] 

 1  newlist = [x.upper() for x in fruits] 

 1 2 3  thislist = ["orange", "mango", "kiwi", "pineapple", "banana"] thislist.sort() print(thislist) 

 1 2 3  thislist = [100, 50, 65, 82, 23] thislist.sort(reverse = True) print(thislist) 

 1 2 3 4 5 6  def myfunc(n): return abs(n - 50) thislist = [100, 50, 65, 82, 23] thislist.sort(key = myfunc) print(thislist) 

 1 2 3  thislist = ["banana", "Orange", "Kiwi", "cherry"] thislist.sort(key = str.lower) #case insensitive print(thislist) 

 1 2  if key(a) > key(b): a,b = b,a #swap the objects 

 1 2 3  thislist = ["banana", "Orange", "Kiwi", "cherry"] thislist.reverse() print(thislist) 

 1 2 3  thislist = ["apple", "banana", "cherry"] mylist = thislist.copy() print(mylist) 

 1 2 3  thislist = ["apple", "banana", "cherry"] mylist = list(thislist) print(mylist) 

 1 2 3 4 5  list1 = ["a", "b", "c"] list2 = [1, 2, 3] list3 = list1 + list2 print(list3) 

• append，尾部追加。
• clear，清空。
• copy，生成副本。
• count，数数用的。
• extend，连接两个数组。
• index，查找第一个满足条件的元素的下标。
• insert，插入。
• pop，按下标删除。
• remove，按值删除。
• reverse，翻转。
• sort，排序。

### 元组(Tuple)

 1 2  thistuple = ("apple", "banana", "cherry") print(thistuple) 

List 不同的是，单元素的元组声明时，必须加一个句号，否则不会识别为元组。

 1 2 3 4 5 6  myList = ["list"] myTuple = ("tuple") #not Tuple! myRealTuple = ("tuple",) #is Tuple! print(type(myList)) print(type(myTuple)) print(type(myRealTuple)) 

 1 2  thistuple = tuple(("apple", "banana", "cherry")) # note the double round-brackets print(thistuple) 

 1 2 3 4 5 6  x = ("apple", "banana", "cherry") y = list(x) y[1] = "kiwi" x = tuple(y) print(x) 

 1 2 3 4 5 6  fruits = ("apple", "banana", "cherry") (green, yellow, red) = fruits print(green) print(yellow) print(red) 

  1 2 3 4 5 6 7 8 9 10  tuple1 = ("a", "b" , "c") tuple2 = (1, 2, 3) tuple3 = tuple1 + tuple2 print(tuple3) fruits = ("apple", "banana", "cherry") mytuple = fruits * 2 #interesting multiply <=> mytuple = fruits + fruits + ... times. print(mytuple) 

### 集合(Sets)

 1 2  thisset = {"apple", "banana", "cherry"} print(thisset) 

 1 2 3 4  thisset = {"apple", "banana", "cherry"} for x in thisset: print(x) 

 1 2 3 4 5  thisset = {"apple", "banana", "cherry"} thisset.add("orange") print(thisset) 

 1 2 3 4 5  thisset = {"apple", "banana", "cherry"} thisset.remove("banana") print(thisset) 

 1 2 3 4 5  thisset = {"apple", "banana", "cherry"} thisset.discard("banana") print(thisset) 

 1 2 3 4 5 6 7  thisset = {"apple", "banana", "cherry"} x = thisset.pop() print(x) print(thisset) 

 1 2 3 4 5 6  thisset = {"apple", "banana", "cherry"} tropical = {"pineapple", "mango", "papaya"} thisset.update(tropical) print(thisset) 

 1 2 3 4 5 6  thisset = {"apple", "banana", "cherry"} mylist = ["kiwi", "orange"] thisset.update(mylist) print(thisset) 

 1 2 3 4 5  set1 = {"a", "b" , "c"} set2 = {1, 2, 3} set3 = set1.union(set2) print(set3) 

 1 2 3 4 5 6 7  x = {"apple", "banana", "cherry"} y = {"google", "microsoft", "apple"} z = x.intersection(y) #like union x.intersection_update(y) #like update print(x) 

 1 2 3 4 5 6 7  x = {"apple", "banana", "cherry"} y = {"google", "microsoft", "apple"} z = x.symmetric_difference(y) x.symmetric_difference_update(y) print(x) 

 1 2 3 4 5  thisset = {"apple", "banana", "cherry"} thisset.clear() print(thisset) del thisset print(thisset) 

### 字典(Dictionary)

3.7 以上的 Python 版本中，字典是有序的。有序性、可变性、不重复性。

 1 2 3 4 5 6 7 8  thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964 } print(thisdict) print(thisdict["brand"]) print(thisdict.get("model")) #the same with the former approach 

 1 2 3 4 5 6  thisdict = { "brand": "Ford", "electric": False, "year": 1964, "colors": ["red", "white", "blue"] } 

 1  x = thisdict.keys() 

  1 2 3 4 5 6 7 8 9 10 11 12 13  car = { "brand": "Ford", "model": "Mustang", "year": 1964 } x = car.keys() print(x) #before the change car["color"] = "white" print(x) #after the change 

values 也是一样的：

  1 2 3 4 5 6 7 8 9 10 11 12 13  car = { "brand": "Ford", "model": "Mustang", "year": 1964 } x = car.values() print(x) #before the change car["year"] = 2020 print(x) #after the change 

  1 2 3 4 5 6 7 8 9 10 11 12 13  car = { "brand": "Ford", "model": "Mustang", "year": 1964 } x = car.items() print(x) #before the change car["year"] = 2020 print(x) #after the change 

 1 2 3 4 5 6 7  thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964 } if "model" in thisdict: print("Yes, 'model' is one of the keys in the thisdict dictionary") 

  1 2 3 4 5 6 7 8 9 10 11 12 13 14  thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964 } another = { "another": "Intersting", "stuff": "Join it" } thisdict.update({"year": 2020}) print(thisdict) thisdict.update(another) print(thisdict) 

 1 2 3 4 5 6 7  thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964 } thisdict.pop("model") print(thisdict) 

  1 2 3 4 5 6 7 8 9 10 11  thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964 } thisdict.popitem() print(thisdict) thisdict.update({"new":"I'm newer"}) print(thisdict) thisdict.popitem() print(thisdict) 

 1 2 3 4 5 6 7  thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964 } del thisdict["model"] print(thisdict) 

 1 2 3 4 5 6 7  thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964 } thisdict.clear() print(thisdict) 

 1 2  for x in thisdict: print(x) 

 1 2  for x in thisdict: print(thisdict[x]) #have to search for the value each time executed 

 1 2 3 4  for x in thisdict.values(): print(x) for x in thisdict.keys(): print(x) 

 1 2  for x, y in thisdict.items(): print(x, y) 

 1 2 3 4 5 6 7 8 9  thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964 } mydict = thisdict.copy() print(mydict) mydict = dict(thisdict) print(mydict) 

  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20  child1 = { "name" : "Emil", "year" : 2004 } child2 = { "name" : "Tobias", "year" : 2007 } child3 = { "name" : "Linus", "year" : 2011 } myfamily = { "child1" : child1, "child2" : child2, "child3" : child3 } print(myfamily["child1"]["name"]) 

## 函数(Functions)

 1 2 3  def my_function(): print("Hello from a function") my_function() 

 1 2 3 4 5 6  def my_function(fname): print(fname + " Refsnes") my_function("Emil") my_function("Tobias") my_function("Linus") 

 1 2 3 4  def my_function(*kids): print("The youngest child is " + kids[2]) my_function("Emil", "Tobias", "Linus") 

 1 2 3 4  def my_function(child3, child2, child1): print("The youngest child is " + child3) my_function(child1 = "Emil", child2 = "Tobias", child3 = "Linus") 

 1 2 3 4  def my_function(**kid): print("His last name is " + kid["lname"]) my_function(fname = "Tobias", lname = "Refsnes") 

 1 2 3 4 5 6 7  def my_function(country = "Norway"): print("I am from " + country) my_function("Sweden") my_function("India") my_function() my_function("Brazil") 

 1 2 3 4 5 6 7  def my_function(food): for x in food: print(x) fruits = ["apple", "banana", "cherry"] my_function(fruits) 

 1 2  def my_function(x): return 5 * x 

 1 2  def myfunction(): pass 

## Lambda 表达式

 1  lambda arguments : expression 

 1 2  x = lambda a : a + 10 print(x(5)) 

 1 2  x = lambda a, b, c : a + b + c print(x(5, 6, 2)) 

 1 2 3 4 5 6 7 8  def myfunc(n): return lambda a : a * n mydoubler = myfunc(2) mytripler = myfunc(3) print(mydoubler(11)) print(mytripler(11)) 

## 类和对象(Classes/Objects)

Python 是一个面向对象(Object Oriented)的语言。

 1 2 3 4 5  class MyClass: x = 5 p1 = MyClass() print(p1.x) 

 1 2 3 4 5 6 7 8 9  class Person: def __init__(self, name, age): self.name = name self.age = age p1 = Person("John", 36) print(p1.name) print(p1.age) 

  1 2 3 4 5 6 7 8 9 10  class Person: def __init__(self, name, age): self.name = name self.age = age def myfunc(self): print("Hello my name is " + self.name) p1 = Person("John", 36) p1.myfunc() 

  1 2 3 4 5 6 7 8 9 10  class Person: def __init__(mysillyobject, name, age): mysillyobject.name = name mysillyobject.age = age def myfunc(abc): print("Hello my name is " + abc.name) p1 = Person("John", 36) p1.myfunc() 

 1  del p1.age 

 1  del p1 

 1 2  class Person: pass 

## 继承(Inheritance)

  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32  class Person: def __init__(self, fname, lname): self.firstname = fname self.lastname = lname def printname(self): print(self.firstname, self.lastname) #Use the Person class to create an object, and then execute the printname method: x = Person("John", "Doe") x.printname() class Student(Person): def __init__(self, fname, lname, year): # overwrite parent's __init__ super().__init__(fname, lname) # <=> Person.__init__(self, fname, lname) self.graduationyear = year def welcome(self): print("Welcome", self.firstname, self.lastname, "to the class of", self.graduationyear) def printname(self): super().printname() print("plus {} is a student!".format(self.lastname)) x = Student("Mike", "Olsen", 2020) x.welcome() x.printname() 

## 迭代器(Iterators)

 1 2 3 4 5 6  mytuple = ("apple", "banana", "cherry") myit = iter(mytuple) print(next(myit)) print(next(myit)) print(next(myit)) 

  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18  class MyNumbers: def __iter__(self): self.a = 1 return self def __next__(self): if self.a <= 20: x = self.a self.a += 1 return x else: raise StopIteration #Stop iterating myclass = MyNumbers() myiter = iter(myclass) for x in myiter: print(x) 

## 定义域(Scope)

 1 2 3 4 5  def myfunc(): x = 300 print(x) myfunc() 

 1 2 3 4 5 6 7  def myfunc(): x = 300 def myinnerfunc(): print(x) myinnerfunc() myfunc() 

 1 2 3 4 5 6 7 8  x = 300 def myfunc(): print(x) myfunc() print(x) 

  1 2 3 4 5 6 7 8 9 10 11 12 13 14  x = 300 def myfunc(): global x x = 200 def myfunc2(): x = 400 print(x) myfunc() myfunc2() print(x) 

## 模块(Modules)

 1 2 3 4 5 6 7  person1 = { "name": "John", "age": 36, "country": "Norway" } def greeting(name): print("Hello, " + name) 

 1 2 3 4 5  import mymodule mymodule.greeting("Jonathan") a = mymodule.person1["age"] print(a) 

 1 2 3 4  import mymodule as mx a = mx.person1["age"] print(a) 

 1 2 3 4 5 6  import platform x = platform.system() print(x) x = dir(platform) print(x) 

 1 2 3  from mymodule import person1 print (person1["age"]) #print(mymodule.person1["age"]) WRONG!! 

 1 2  from mymodule import person1 as p1 print (p1["age"]) 

## PIP

 1 2 3 4 5 6 7  import camelcase c = camelcase.CamelCase() txt = "hello world" print(c.hump(txt)) 

## 异常捕获(Try…Except)

  1 2 3 4 5 6 7 8 9 10  try: print(x) except NameError: print("Variable x is not defined") except: print("Something else went wrong") else: print("Nothing went wrong") finally: print("Ended.") 

 1 2 3 4 5 6 7  try: f = open("demofile.txt") f.write("Lorum Ipsum") except: print("Something went wrong when writing to the file") finally: f.close() 

 1 2 3 4  x = -1 if x < 0: raise Exception("Sorry, no numbers below zero") 

 1 2 3 4  x = "hello" if not type(x) is int: raise TypeError("Only integers are allowed") 

## 输入(Input)

 1 2  username = input("Enter username:") print("Username is: " + username) 

## 格式化字符串(Formatting)

 1 2 3  price = 49 txt = "The price is {} dollars" print(txt.format(price)) 

 1 2 3 4 5  quantity = 3 itemno = 567 price = 49 myorder = "I want {0} pieces of item number {1} for {2:.2f} dollars." print(myorder.format(quantity, itemno, price)) 

 1 2 3 4  age = 36 name = "John" txt = "His name is {1}. {1} is {0} years old." print(txt.format(age, name)) 

 1 2  myorder = "I have a {carname}, it is a {model}." print(myorder.format(carname = "Ford", model = "Mustang"))