前言

转载于本人博客

面向有编程经验者的极速入门指南。

大部分内容简化于 W3School,翻译不一定准确,因此标注了英文。

包括代码一共两万字符左右,预计阅读时间一小时。

目前我的博客长文显示效果不佳,缺乏目录,因此可以考虑下载阅读。博客完全开源于 Github.

语法(Syntax)

文件执行方式:python myfile.py

强制缩进,缩进不能省略。缩进可以使用任意数量的空格。

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

注释(Comment)

注释语法:

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

变量(Variables)

当变量被赋值时,其被创建。

没有显式声明变量的语法。

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

可以转换类型。

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

可以获得类型。

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

还可以这样赋值:

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

没有在函数中声明的变量一律视作全局变量。

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

局部变量优先。

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

也可以显式声明全局变量。

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

由于不能区分赋值和声明,因此如果在函数中修改全局变量,需要指明全局。

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

数值(Number)

三种数值类型:int float complex

其中复数的虚部用 j 来表示。

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

真值(Boolean)

使用 TrueFalse,大小写敏感。

可以强制转换:

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

空值一般转换为假,例如零、空文本、空集合等。

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

大于小于等于不等于跟 C 语言一致。

如果:

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

适当压行也是可以的:

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

三目运算符,需要注意的是执行语句在前面。

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

与或:

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

如果不能为空,可以传递个 pass 占位。

  1. if b > a:
  2. pass

while 循环很常规:

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

还有个 else 的语法:

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

这个有什么用呢?其实是可以判断自然结束还是被打断。

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

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

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

为了循环,可以用 range 生成一个数组。依然是左闭右开。可以缺省左边界 0.

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

可以指定步长,默认为 1.

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

也支持 else

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

也可以拿 pass 占位。

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

字符串(String)

有两种写法:

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

好像没什么区别。

多行字符串:

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

字符串可以直接当数组用。

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

获得长度。

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

直接搜索。

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

几个常用函数:

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

连接两个字符串,直接用加号。

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

格式化:

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

可以指定参数填入的顺序:

  1. myorder = "I want to pay {2} dollars for {0} pieces of item {1}."
  2. 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)

没有 Array,只有 List.

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

下标从零开始。

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

还可以是负的,-1 表示倒数第一个,依此类推。

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

获取子数组,左闭右开。例如 [2:5] 代表 [2,5)

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

还可以去头去尾。

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

获得元素个数:

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

元素类型都可以不同:

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

构造:

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

赋值:

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

甚至一次改变一个子数组:

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

元素数量可以不对等,可以视作将原数组中的 [l,r) 扔掉,然后从切口塞进去新的子数组。

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

支持插入,应该是 \(O(n)\) 复杂度的。insert(x,"something") 即让 something 成为下标为 x 的元素,也就是插入到当前下标为 x 的元素前。

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

尾部追加,应该是 \(O(1)\) 的。

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

直接连接两个数组:

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

啥都能连接?

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

删除,一次只删一个。

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

按下标删除。可以省略参数,默认删除最后一个。

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

还可以用 del 关键字。

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

清空,数组对象依然保留。

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

可以直接用 for 来遍历。

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

也可以用下标遍历。

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

为了性能,也可以用 while 来遍历,避免 range 生成过大的数组。

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

缩写的 for 遍历,两边中括号是必须的。

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

赋值的时候,也有一些神奇的语法糖:

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

更抽象地:

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

还是比较灵活的:

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

支持直接排序。

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

排序也有一些参数。

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

可以自定义估值函数,返回一个对象用于比较?

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

还有这样的:

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

所以其实排序内部可能是这样的:

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

翻转数组:

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

直接拷贝只能拷贝到引用,所以有拷贝数组:

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

也可以直接构造:

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

合并:

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

总结一下内置函数:

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

元组(Tuple)

元组可以看作是不可修改的 List.

用圆括号包裹。

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

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

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

构造:

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

元组是不可变的(immutable),想要修改只能变成 List,改完再生成元组。当然这样做效率很低。

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

当我们创建元组时,我们将变量填入,这被称为「打包(packing)」.

而我们也可以将元组重新解析为变量,这被称为「解包(unpacking)」.

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

有趣的是,元组不能修改,却能连接,这大概是因为运算过程产生了新的元组而作为返回值。

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

集合(Sets)

这个集合是数学意义上的集合,即具有无序性、不重复性、确定性的特性的集合。

用大括号:

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

集合不支持下标访问,只能遍历:

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

不能修改元素,但可以添加元素。也可以删除再添加来达到修改的效果。

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

简单的删除 remove,如果删除的元素不存在会报错。

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

如果不想要报错,可以用 discard

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

甚至可以用 pop,由于无序性,可能会随机删除一个元素?

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

取并集,也就是合并两个集合,需要使用 update,合并后会去重。

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

当然合并不仅限于集合之间。

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

如果不想影响原集合,只需要返回值,可以用 union

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

取交集:

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

还有更有趣的,删去交集,即 \((\mathbb{A} \cup \mathbb{B}) \setminus (\mathbb{A} \cap \mathbb{B})\)

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

清空和彻底删除:

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

字典(Dictionary)

类似于 C++ 中的 map,键值对。

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

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

有趣的是,值可以是任意数据类型。

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

获取所有 key

  1. x = thisdict.keys()

值得注意的是,这里传出的是一个引用,也就是说是可以动态更新的。但似乎是只读的。

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

values 也是一样的:

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

还可以直接获取所有键值对 items

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

可以查看键是否存在:

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

可以用 update 来更新,支持塞入一个键值对集合:

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

移除特定键:

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

移除最后一个键值对:

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

可以用 del 关键字:

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

清空:

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

遍历所有键名:

  1. for x in thisdict:
  2. print(x)

遍历所有值:

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

直接获取集合来遍历:

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

遍历键值对:

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

深拷贝:

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

嵌套:

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

函数(Functions)

函数定义:

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

参数:

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

形参(Parameter)和实参(Argument).

不定长参数:

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

可以用更优雅的方式传参:

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

实质上是键值对的传递,因此:

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

默认参数:

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

弱类型,啥都能传:

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

返回值:

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

占位符:

  1. def myfunction():
  2. pass

Lambda 表达式

只能有一行表达式,但可以有任意个数参数。

  1. lambda arguments : expression

例如一个自增 \(10\) 的函数:

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

多参数:

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

有趣的是,可以利用 Lambda 表达式构造匿名函数:

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

类和对象(Classes/Objects)

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

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

初始化:

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

声明方法:

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

函数的第一个参数将会是指向自己的引用,并不强制命名为 self.

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

可以删除某个属性:

  1. del p1.age

可以删除对象:

  1. del p1

占位符:

  1. class Person:
  2. pass

继承(Inheritance)

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

迭代器(Iterators)

一个迭代器需要有 __iter____next__ 两个方法。

所有的集合都能提供迭代器,都是可遍历的(Iterable Containers).

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

创建一个迭代器:

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

定义域(Scope)

函数中声明的变量只在函数中有效。

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

事实上,它在该函数的域内有效。

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

全局变量:

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

更多有关全局变量的前文已经说过,这里复习一下。

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

模块(Modules)

调库大法好。

举个例子,在 mymodule.py 中保存以下内容:

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

然后在 main.py 中运行:

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

可以起别名(Alias):

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

有一些内置的模块:

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

可以指定引用模块的某些部分,此时不需要再写模块名:

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

也可以起别名:

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

PIP

包管理器。

安装包:pip install <package-name>

例如:pip install camelcase

然后就能直接使用了:

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

异常捕获(Try...Except)

比较常规。

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

举个例子:

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

抛出异常:

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

可以指定类型:

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

输入(Input)

很简单的输入。

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

格式化字符串(Formatting)

前文已经简单提及了。

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

可以指定输出格式:

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

可以重复利用:

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

可以传键值对:

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

结语

差不多把 Python 中的基础语法过了一遍,相信各位读者读完后都能入门吧。

大部分编程概念都是相似的,学习起来并不困难。这也是一个写起来没什么心智负担的工具语言。有什么需要直接面向谷歌编程即可。

Python 极速入门指南的更多相关文章

  1. 多本Python极速入门最佳书籍,不可错过的Python学习资料!

    Python作为现在很热门的一门编程语言,介于Python的友好,许多的初学者都将其作为首选,为了帮助大家更好的学习Python,我筛选了2年内优秀的python书籍,个别经典的书籍扩展到5年内.   ...

  2. 针对Quant的Python快速入门指南

    作者:用Python的交易员 (原创文章,转载请注明出处) 最近有越来越多的朋友在知乎或者QQ上问我如何学习入门Python,就目前需求来看,我需要写这么一篇指南. 针对整个vn.py框架的学习,整体 ...

  3. 【python】入门指南1

    基础的数据结构:int, float, string 注意:python入门系列的文章的示例均使用python3来完成. #!/bin/python a = 1 b = 1.0 c = 'string ...

  4. 22 【python】入门指南:函数

    #!/bin/python def test_func(): return "test_func" a = test_func() print(a) 输出结果: test_func ...

  5. 20 【python】入门指南:常用数据结构

    Python内置了三种高级数据结构:list,tuple,dict list:数组,相同类型的元素组成的数组 tuple:元组,相同类型的元素组成的数组,但是这里有限定条件(长度是固定的,并且值也是固 ...

  6. 【python】入门指南:控制语句

    条件控制 if,if-else,if-elseif-else #!/bin/python a = 'test' if a == 'test': print('a is %s' %(a)) else: ...

  7. Python不完全入门指南

    适用范围: 有一定编程基础,想快速入门python的人群 说明: 使用jupyter notebook编写,可以使用nbviewer网站进行查看. Python不完全入门指南 项目放在github上, ...

  8. Python 30分钟入门指南

    Python 30分钟入门指南 为什么 OIer 要学 Python? Python 语言特性简洁明了,使用 Python 写测试数据生成器和对拍器,比编写 C++ 事半功倍. Python 学习成本 ...

  9. 《Python黑客编程之极速入门》正式开课

    玄魂 玄魂工作室 今天 之前开启了一个<Python黑客编程>的系列,后来中断了,内容当时设置的比较宽,不太适合入门.现在将其拆分成两个系列<Python黑客编程之极速入门>和 ...

随机推荐

  1. Linux安装jdk(两种方式)

    最近在研究大数据方面的东西,业务场景是从设备采集数据经过处理然后存放DB. 建设上面的环境第一步肯定是安装jdk,所以和大家一起学一下基本知识centos7.5安装jdk1.8. 安装jdk有两种方法 ...

  2. 【Arduino学习笔记06】上拉电阻和下拉电阻

    为什么要用上拉电阻和下拉电阻?--避免输入引脚处于"悬空"状态 下图是一个没有使用上拉电阻/下拉电阻的电路图: 在按键没有按下时,要读取的输入引脚没有连接到任何东西,这种状态就称为 ...

  3. SpringMVC-03 RestFul和控制器

    SpringMVC-03 RestFul和控制器 控制器Controller 控制器复杂提供访问应用程序的行为,通常通过接口定义或注解定义两种方法实现. 控制器负责解析用户的请求并将其转换为一个模型. ...

  4. MindSpore:基于本地差分隐私的 Bandit 算法

    摘要:本文将先简单介绍Bandit 问题和本地差分隐私的相关背景,然后介绍基于本地差分隐私的 Bandit 算法,最后通过一个简单的电影推荐场景来验证 LDP LinUCB 算法. Bandit问题是 ...

  5. FreeBSD 如何让csh像zsh那样具有命令错误修正呢

    比如,,你用 emacs写c ,但你输完emacs ma按tab回车是,他会匹配所有ma开头的文件,而这个是忽略掉,也就是按tab时不会在有你忽略的东西,对编程之类的友好,不用再匹配到二进制..o之类 ...

  6. 从零学脚手架(五)---react、browserslist

    如果此篇对您有所帮助,在此求一个star.项目地址: OrcasTeam/my-cli react react介绍 目前,国内主流的前端应用框架具有两个:vue.js和react.js,关于vue和r ...

  7. flutter简易教程

    跟Java等很多语言不同的是,Dart没有public protected private等关键字,如果某个变量以下划线 _ 开头,代表这个变量在库中是私有的.Dart中变量可以以字母或下划线开头,后 ...

  8. 2.pandas常用读取

    一.文本读写 名称 接收 代表(含义) 默认 filepath string 文件路径 无 sep string 分割符 ',' header Int/sequence 某行做列名 infer自动寻找 ...

  9. ch2_8_4求解投骰子游戏问题

    思路:递推.到第n步可以从第0步走n步到第n步,从第1步走n-1步到第n步... ...依次类推,=> f(n)=f(0)+f(1)+...+f(n-1) import java.util.Sc ...

  10. Windows下解析命令行参数

    linux通常使用GNU C提供的函数getopt.getopt_long.getopt_long_only函数来解析命令行参数. 移植到Windows下 getopt.h #ifndef _GETO ...