属性
Python 是一种强类型(类型强制)、动态、隐式类型(不必声明变量)、大小写敏感、面向对象的语言。
获取帮助
Python 帮助始终在 Python 解释器中可用,想知道一个对象是如何工作的,只需调用 help(<object>)
;dir()
也很有用,它显示对象的所有方法,<object>.__doc__
显示其文档字符串。
>>> help(5)
Help on int object:
(etc)
>>> dir(5)
['__abs__', '__add__', '__and__', ...]
>>> abs.__doc__
'Return the absolute value of the argument.'
语法
Python 没有语句强制终止符,并且块由缩进指定;
期望缩进结束于冒号(:);
注释以 # 开始,多行字符串用于多行注释;
变量赋值用等号(=),测试相等用两个等号(==);
变量递增/递减用 +=/-= ,适用于多种数据类型,如字符串;
可以在一行使用多个变量,如 a, b = b, a
>>> myvar = 3
>>> myvar += 2
>>> myvar
5
>>> myvar -= 1
>>> myvar
4
"""This is a multiline comment.
The following lines concatenate the two strings."""
>>> mystring = "Hello"
>>> mystring += " world."
>>> print(mystring)
Hello world.
# This swaps the variables in one line(!).
# It doesn't violate strong typing because values aren't
# actually being assigned, but new objects are bound to
# the old names.
>>> myvar, mystring = mystring, myvar
数据类型
Python 中可用的数据结构包括列表、元组和字典,sets
套件中提供集(但内置于 Python 2.5 及更晚版本);
列表就像一维数组(但也可以有其他列表的列表);
字典是关联数组(也称为哈希表);
元组是不可变的一维数组;
Python “数组”可以是任何类型的,因此可以在列表/字典/元组中混合例如整数、字符串等;
所有数组类型中第一项的索引为 0,-1 是最后一项;
变量可以指向函数
>>> sample = [1, ["another", "list"], ("a", "tuple")]
>>> mylist = ["List item 1", 2, 3.14]
>>> mylist[0] = "List item 1 again" # We're changing the item.
>>> mylist[-1] = 3.21 # Here, we refer to the last item.
>>> mydict = {"Key 1": "Value 1", 2: 3, "pi": 3.14}
>>> mydict["pi"] = 3.15 # This is how you change dictionary values.
>>> mytuple = (1, 2, 3)
>>> myfunction = len
>>> print(myfunction(mylist))
3
>>> mylist = ["List item 1", 2, 3.14]
>>> print(mylist[:])
['List item 1', 2, 3.1400000000000001]
>>> print(mylist[0:2])
['List item 1', 2]
>>> print(mylist[-3:-1])
['List item 1', 2]
>>> print(mylist[1:])
[2, 3.14]
# Adding a third parameter, "step" will have Python step in
# N item increments, rather than 1.
# E.g., this will return the first item, then go to the third and
# return that (so, items 0 and 2 in 0-indexing).
>>> print(mylist[::2])
['List item 1', 3.14]