参考:Learn Python in 10 minutes

属性

Python 是一种强类型(类型强制)、动态隐式类型(不必声明变量)、大小写敏感面向对象的语言。

获取帮助

Python 帮助始终在 Python 解释器中可用,想知道一个对象是如何工作的,只需调用 help(<object>)dir() 也很有用,它显示对象的所有方法<object>.__doc__ 显示其文档字符串

  1. >>> help(5)
  2. Help on int object:
  3. (etc)
  4. >>> dir(5)
  5. ['__abs__', '__add__', '__and__', ...]
  6. >>> abs.__doc__
  7. 'Return the absolute value of the argument.'

语法

Python 没有语句强制终止符,并且块由缩进指定;
期望缩进结束于冒号(:);
注释以 # 开始,多行字符串用于多行注释;
变量赋值用等号(=),测试相等用两个等号(==);
变量递增/递减用 +=/-= ,适用于多种数据类型,如字符串;
可以在一行使用多个变量,如 a, b = b, a

  1. >>> myvar = 3
  2. >>> myvar += 2
  3. >>> myvar
  4. 5
  5. >>> myvar -= 1
  6. >>> myvar
  7. 4
  8. """This is a multiline comment.
  9. The following lines concatenate the two strings."""
  10. >>> mystring = "Hello"
  11. >>> mystring += " world."
  12. >>> print(mystring)
  13. Hello world.
  14. # This swaps the variables in one line(!).
  15. # It doesn't violate strong typing because values aren't
  16. # actually being assigned, but new objects are bound to
  17. # the old names.
  18. >>> myvar, mystring = mystring, myvar

数据类型

Python 中可用的数据结构包括列表、元组和字典sets 套件中提供(但内置于 Python 2.5 及更晚版本);
列表就像一维数组(但也可以有其他列表的列表);
字典是关联数组(也称为哈希表);
元组是不可变的一维数组;
Python “数组”可以是任何类型的,因此可以在列表/字典/元组中混合例如整数、字符串等;
所有数组类型中第一项的索引为 0,-1 是最后一项;
变量可以指向函数

  1. >>> sample = [1, ["another", "list"], ("a", "tuple")]
  2. >>> mylist = ["List item 1", 2, 3.14]
  3. >>> mylist[0] = "List item 1 again" # We're changing the item.
  4. >>> mylist[-1] = 3.21 # Here, we refer to the last item.
  5. >>> mydict = {"Key 1": "Value 1", 2: 3, "pi": 3.14}
  6. >>> mydict["pi"] = 3.15 # This is how you change dictionary values.
  7. >>> mytuple = (1, 2, 3)
  8. >>> myfunction = len
  9. >>> print(myfunction(mylist))
  10. 3
  1. >>> mylist = ["List item 1", 2, 3.14]
  2. >>> print(mylist[:])
  3. ['List item 1', 2, 3.1400000000000001]
  4. >>> print(mylist[0:2])
  5. ['List item 1', 2]
  6. >>> print(mylist[-3:-1])
  7. ['List item 1', 2]
  8. >>> print(mylist[1:])
  9. [2, 3.14]
  10. # Adding a third parameter, "step" will have Python step in
  11. # N item increments, rather than 1.
  12. # E.g., this will return the first item, then go to the third and
  13. # return that (so, items 0 and 2 in 0-indexing).
  14. >>> print(mylist[::2])
  15. ['List item 1', 3.14]