Python基础二. 数据结构、控制流、运算符、真值测试

时间:2023-03-10 02:54:06
Python基础二. 数据结构、控制流、运算符、真值测试

一、概述

数据结构上广义上有两种,单一类型和集合类型

  • 单一类型,表示一种对象
  • 集合类型,表示包含多种对象

Python 中的内建的数据类型有str、list、tuple、dict、set、number、bool、None,又可以划分为序列型、可变与不可变

序列型

  • 有序, 数字索引,通过索引取值、切片,都可以迭代, str/list/tuple
  • 无序, 没有数字索引, set/dict

可变与不可变

  • 不可变的对象, 不能原处修改,  如str、tuple、number,修改会重新开辟内存空间
  • 可变的对象, 可以原处修改, 如list、dict、set

切片

  • [i:j:k]   #起始:结束:步长
  • [::-1]       #负偏移,反向
  • [:]           #拷贝方式

迭代

迭代是重复反馈的结果直到没有,序列型的数据都可以迭代,number(数字)对象不可以迭代, 一般用for迭代

对象与类

  • 一切皆对象
  • 每种数据类型是一个类,提供了对象的方法和属性
  • 对象都有自己的命名空间和属性
  • 每种数据类型提供的方法是解决的场景

帮助

  • help() 帮助
  • type() 查看对象的类型
  • dir() 查看对象的属性和方法

  即对象.方法

二、内置数据类型

number

number,数字是不可变的对象,用来计数、数学运算. 数字又分为int(整数)、float(浮点)、long(长整数)

常用功能:

  • 数学运算, 加减乘除商余数..
  • 转换
  • 内置方法
class int(object)
 |  int(x=0) -> int or long
 |  int(x, base=10) -> int or long
 |
 |  Convert a number or string to an integer, or return 0 if no arguments
 |  are given.  If x is floating point, the conversion truncates towards zero.
 |  If x is outside the integer range, the function returns a long instead.
 |
 |  If x is not a number or if base is given, then x must be a string or
 |  Unicode object representing an integer literal in the given base.  The
 |  literal can be preceded by '+' or '-' and be surrounded by whitespace.
 |  The base defaults to 10.  Valid bases are 0 and 2-36.  Base 0 means to
 |  interpret the base from the string as an integer literal.
 |  >>> int('0b100', base=0)
 |  4
 |
 |  Methods defined here:
 |
 |  __abs__(...)
 |      x.__abs__() <==> abs(x)
 |
 |  __add__(...)
 |      x.__add__(y) <==> x+y
 |
 |  __and__(...)
 |      x.__and__(y) <==> x&y
 |
 |  __cmp__(...)
 |      x.__cmp__(y) <==> cmp(x,y)
 |
 |  __coerce__(...)
 |      x.__coerce__(y) <==> coerce(x, y)
 |
 |  __div__(...)
 |      x.__div__(y) <==> x/y
 |
 |  __divmod__(...)
 |      x.__divmod__(y) <==> divmod(x, y)
 |
 |  __float__(...)
 |      x.__float__() <==> float(x)
 |
 |  __floordiv__(...)
 |      x.__floordiv__(y) <==> x//y
 |
 |  __format__(...)
 |
 |  __getattribute__(...)
 |      x.__getattribute__('name') <==> x.name
 |
 |  __getnewargs__(...)
 |
 |  __hash__(...)
 |      x.__hash__() <==> hash(x)
 |
 |  __hex__(...)
 |      x.__hex__() <==> hex(x)
 |
 |  __index__(...)
 |      x[y:z] <==> x[y.__index__():z.__index__()]
 |
 |  __int__(...)
 |      x.__int__() <==> int(x)
 |
 |  __invert__(...)
 |      x.__invert__() <==> ~x
 |
 |  __long__(...)
 |      x.__long__() <==> long(x)
 |
 |  __lshift__(...)
 |      x.__lshift__(y) <==> x<<y
 |
 |  __mod__(...)
 |      x.__mod__(y) <==> x%y
 |
 |  __mul__(...)
 |      x.__mul__(y) <==> x*y
 |
 |  __neg__(...)
 |      x.__neg__() <==> -x
 |
 |  __nonzero__(...)
 |      x.__nonzero__() <==> x != 0
 |
 |  __oct__(...)
 |      x.__oct__() <==> oct(x)
 |
 |  __or__(...)
 |      x.__or__(y) <==> x|y
 |
 |  __pos__(...)
 |      x.__pos__() <==> +x
 |
 |  __pow__(...)
 |      x.__pow__(y[, z]) <==> pow(x, y[, z])
 |
 |  __radd__(...)
 |      x.__radd__(y) <==> y+x
 |
 |  __rand__(...)
 |      x.__rand__(y) <==> y&x
 |
 |  __rdiv__(...)
 |      x.__rdiv__(y) <==> y/x
 |
 |  __rdivmod__(...)
 |      x.__rdivmod__(y) <==> divmod(y, x)
 |
 |  __repr__(...)
 |      x.__repr__() <==> repr(x)
 |
 |  __rfloordiv__(...)
 |      x.__rfloordiv__(y) <==> y//x
 |
 |  __rlshift__(...)
 |      x.__rlshift__(y) <==> y<<x
 |
 |  __rmod__(...)

int对象的内置方法

class float(object)
 |  float(x) -> floating point number
 |
 |  Convert a string or number to a floating point number, if possible.
 |
 |  Methods defined here:
 |
 |  __abs__(...)
 |      x.__abs__() <==> abs(x)
 |
 |  __add__(...)
 |      x.__add__(y) <==> x+y
 |
 |  __coerce__(...)
 |      x.__coerce__(y) <==> coerce(x, y)
 |
 |  __div__(...)
 |      x.__div__(y) <==> x/y
 |
 |  __divmod__(...)
 |      x.__divmod__(y) <==> divmod(x, y)
 |
 |  __eq__(...)
 |      x.__eq__(y) <==> x==y
 |
 |  __float__(...)
 |      x.__float__() <==> float(x)
 |
 |  __floordiv__(...)
 |      x.__floordiv__(y) <==> x//y
 |
 |  __format__(...)
 |      float.__format__(format_spec) -> string
 |
 |      Formats the float according to format_spec.
 |
 |  __ge__(...)
 |      x.__ge__(y) <==> x>=y
 |
 |  __getattribute__(...)
 |      x.__getattribute__('name') <==> x.name
 |
 |  __getformat__(...)
 |      float.__getformat__(typestr) -> string
 |
 |      You probably don't want to use this function.  It exists mainly to be
 |      used in Python's test suite.
 |
 |      typestr must be 'double' or 'float'.  This function returns whichever of
 |      'unknown', 'IEEE, big-endian' or 'IEEE, little-endian' best describes the
 |      format of floating point numbers used by the C type named by typestr.
 |
 |  __getnewargs__(...)
 |
 |  __gt__(...)
 |      x.__gt__(y) <==> x>y
 |
 |  __hash__(...)
 |      x.__hash__() <==> hash(x)
 |
 |  __int__(...)
 |      x.__int__() <==> int(x)
 |
 |  __le__(...)
 |      x.__le__(y) <==> x<=y
 |
 |  __long__(...)
 |      x.__long__() <==> long(x)
 |
 |  __lt__(...)
 |      x.__lt__(y) <==> x<y
 |
 |  __mod__(...)
 |      x.__mod__(y) <==> x%y
 |
 |  __mul__(...)
 |      x.__mul__(y) <==> x*y
 |
 |  __ne__(...)
 |      x.__ne__(y) <==> x!=y
 |
 |  __neg__(...)
 |      x.__neg__() <==> -x
 |
 |  __nonzero__(...)
 |      x.__nonzero__() <==> x != 0
 |
 |  __pos__(...)
 |      x.__pos__() <==> +x
 |
 |  __pow__(...)
 |      x.__pow__(y[, z]) <==> pow(x, y[, z])
 |
 |  __radd__(...)
 |      x.__radd__(y) <==> y+x
 |
 |  __rdiv__(...)
 |      x.__rdiv__(y) <==> y/x
 |
 |  __rdivmod__(...)
 |      x.__rdivmod__(y) <==> divmod(y, x)
 |
 |  __repr__(...)
 |      x.__repr__() <==> repr(x)
 |
 |  __rfloordiv__(...)
 |      x.__rfloordiv__(y) <==> y//x
 |
 |  __rmod__(...)
 |      x.__rmod__(y) <==> y%x
 |
 |  __rmul__(...)
 |      x.__rmul__(y) <==> y*x
 |
 |  __rpow__(...)
 |      y.__rpow__(x[, z]) <==> pow(x, y[, z])
 |
 |  __rsub__(...)
 |      x.__rsub__(y) <==> y-x
 |
 |  __rtruediv__(...)
 |      x.__rtruediv__(y) <==> y/x
 |
 |  __setformat__(...)
 |      float.__setformat__(typestr, fmt) -> None
 |
 |      You probably don't want to use this function.  It exists mainly to be
 |      used in Python's test suite.
 |
 |      typestr must be 'double' or 'float'.  fmt must be one of 'unknown',
 |      'IEEE, big-endian' or 'IEEE, little-endian', and in addition can only be
 |      one of the latter two if it appears to match the underlying C reality.
 |
 |      Override the automatic determination of C-level floating point type.
 |      This affects how floats are converted to and from binary strings.
 |
 |  __str__(...)
 |      x.__str__() <==> str(x)
 |
 |  __sub__(...)
 |      x.__sub__(y) <==> x-y
 |
 |  __truediv__(...)
 |      x.__truediv__(y) <==> x/y
 |
 |  __trunc__(...)
 |      Return the Integral closest to x between 0 and x.
 |
 |  as_integer_ratio(...)
 |      float.as_integer_ratio() -> (int, int)
 |
 |      Return a pair of integers, whose ratio is exactly equal to the original
 |      float and with a positive denominator.
 |      Raise OverflowError on infinities and a ValueError on NaNs.
 |
 |      >>> (10.0).as_integer_ratio()
 |      (10, 1)
 |      >>> (0.0).as_integer_ratio()
 |      (0, 1)
 |      >>> (-.25).as_integer_ratio()
 |      (-1, 4)
 |
 |  conjugate(...)
 |      Return self, the complex conjugate of any float.
 |
 |  fromhex(...)
 |      float.fromhex(string) -> float
 |
 |      Create a floating-point number from a hexadecimal string.
 |      >>> float.fromhex('0x1.ffffp10')
 |      2047.984375
 |      >>> float.fromhex('-0x1p-1074')
 |      -4.9406564584124654e-324
 |
 |  hex(...)
 |      float.hex() -> string
 |
 |      Return a hexadecimal representation of a floating-point number.
 |      >>> (-0.1).hex()
 |      '-0x1.999999999999ap-4'
 |      >>> 3.14159.hex()
 |      '0x1.921f9f01b866ep+1'
 |
 |  is_integer(...)
 |      Return True if the float is an integer.
 |
 |  ----------------------------------------------------------------------
 |  Data descriptors defined here:
 |
 |  imag
 |      the imaginary part of a complex number
 |
 |  real
 |      the real part of a complex number
 |
 |  ----------------------------------------------------------------------
 |  Data and other attributes defined here:
 |
 |  __new__ = <built-in method __new__ of type object>
 |      T.__new__(S, ...) -> a new object with type S, a subtype of T

float对象的内置方法

class long(object)
 |  long(x=0) -> long
 |  long(x, base=10) -> long
 |
 |  Convert a number or string to a long integer, or return 0L if no arguments
 |  are given.  If x is floating point, the conversion truncates towards zero.
 |
 |  If x is not a number or if base is given, then x must be a string or
 |  Unicode object representing an integer literal in the given base.  The
 |  literal can be preceded by '+' or '-' and be surrounded by whitespace.
 |  The base defaults to 10.  Valid bases are 0 and 2-36.  Base 0 means to
 |  interpret the base from the string as an integer literal.
 |  >>> int('0b100', base=0)
 |  4L
 |
 |  Methods defined here:
 |
 |  __abs__(...)
 |      x.__abs__() <==> abs(x)
 |
 |  __add__(...)
 |      x.__add__(y) <==> x+y
 |
 |  __and__(...)
 |      x.__and__(y) <==> x&y
 |
 |  __cmp__(...)
 |      x.__cmp__(y) <==> cmp(x,y)
 |
 |  __coerce__(...)
 |      x.__coerce__(y) <==> coerce(x, y)
 |
 |  __div__(...)
 |      x.__div__(y) <==> x/y
 |
 |  __divmod__(...)
 |      x.__divmod__(y) <==> divmod(x, y)
 |
 |  __float__(...)
 |      x.__float__() <==> float(x)
 |
 |  __floordiv__(...)
 |      x.__floordiv__(y) <==> x//y
 |
 |  __format__(...)
 |
 |  __getattribute__(...)
 |      x.__getattribute__('name') <==> x.name
 |
 |  __getnewargs__(...)
 |
 |  __hash__(...)
 |      x.__hash__() <==> hash(x)
 |
 |  __hex__(...)
 |      x.__hex__() <==> hex(x)
 |
 |  __index__(...)
 |      x[y:z] <==> x[y.__index__():z.__index__()]
 |
 |  __int__(...)
 |      x.__int__() <==> int(x)
 |
 |  __invert__(...)
 |      x.__invert__() <==> ~x
 |
 |  __long__(...)
 |      x.__long__() <==> long(x)
 |
 |  __lshift__(...)
 |      x.__lshift__(y) <==> x<<y
 |
 |  __mod__(...)
 |      x.__mod__(y) <==> x%y
 |
 |  __mul__(...)
 |      x.__mul__(y) <==> x*y
 |
 |  __neg__(...)
 |      x.__neg__() <==> -x
 |
 |  __nonzero__(...)
 |      x.__nonzero__() <==> x != 0
 |
 |  __oct__(...)
 |      x.__oct__() <==> oct(x)
 |
 |  __or__(...)
 |      x.__or__(y) <==> x|y
 |
 |  __pos__(...)
 |      x.__pos__() <==> +x
 |
 |  __pow__(...)
 |      x.__pow__(y[, z]) <==> pow(x, y[, z])
 |
 |  __radd__(...)
 |      x.__radd__(y) <==> y+x
 |
 |  __rand__(...)
 |      x.__rand__(y) <==> y&x
 |
 |  __rdiv__(...)
 |      x.__rdiv__(y) <==> y/x
 |
 |  __rdivmod__(...)
 |      x.__rdivmod__(y) <==> divmod(y, x)
 |
 |  __repr__(...)
 |      x.__repr__() <==> repr(x)
 |
 |  __rfloordiv__(...)
 |      x.__rfloordiv__(y) <==> y//x
 |
 |  __rlshift__(...)
 |      x.__rlshift__(y) <==> y<<x
 |
 |  __rmod__(...)
 |      x.__rmod__(y) <==> y%x
 |
 |  __rmul__(...)
 |      x.__rmul__(y) <==> y*x
 |
 |  __ror__(...)
 |      x.__ror__(y) <==> y|x
 |
 |  __rpow__(...)
 |      y.__rpow__(x[, z]) <==> pow(x, y[, z])
 |
 |  __rrshift__(...)
 |      x.__rrshift__(y) <==> y>>x
 |
 |  __rshift__(...)
 |      x.__rshift__(y) <==> x>>y
 |
 |  __rsub__(...)
 |      x.__rsub__(y) <==> y-x
 |
 |  __rtruediv__(...)
 |      x.__rtruediv__(y) <==> y/x
 |
 |  __rxor__(...)
 |      x.__rxor__(y) <==> y^x
 |
 |  __sizeof__(...)
 |      Returns size in memory, in bytes
 |
 |  __str__(...)
 |      x.__str__() <==> str(x)
 |
 |  __sub__(...)
 |      x.__sub__(y) <==> x-y
 |
 |  __truediv__(...)
 |      x.__truediv__(y) <==> x/y
 |
 |  __trunc__(...)
 |      Truncating an Integral returns itself.
 |
 |  __xor__(...)
 |      x.__xor__(y) <==> x^y
 |
 |  bit_length(...)
 |      long.bit_length() -> int or long
 |
 |      Number of bits necessary to represent self in binary.
 |      >>> bin(37L)
 |      '0b100101'
 |      >>> (37L).bit_length()
 |      6
 |
 |  conjugate(...)
 |      Returns self, the complex conjugate of any long.
 |
 |  ----------------------------------------------------------------------
 |  Data descriptors defined here:
 |
 |  denominator
 |      the denominator of a rational number in lowest terms
 |
 |  imag
 |      the imaginary part of a complex number
 |
 |  numerator
 |      the numerator of a rational number in lowest terms
 |
 |  real
 |      the real part of a complex number
 |
 |  ----------------------------------------------------------------------
 |  Data and other attributes defined here:
 |
 |  __new__ = <built-in method __new__ of type object>
 |      T.__new__(S, ...) -> a new object with type S, a subtype of T

long对象的内置方法

str

str是有序不可变对象,可以通过索引取值、切片及迭代.

常用的功能:

  • 格式化、拼接
  • 切片
  • 长度
  • 重复
  • 成员关系
  • 迭代
  • 内置方法
class str(basestring)
 |  str(object='') -> string
 |
 |  Return a nice string representation of the object.
 |  If the argument is a string, the return value is the same object.
 |
 |  Method resolution order:
 |      str
 |      basestring
 |      object
 |
 |  Methods defined here:
 |
 |  __add__(...)
 |      x.__add__(y) <==> x+y
 |
 |  __contains__(...)
 |      x.__contains__(y) <==> y in x
 |
 |  __eq__(...)
 |      x.__eq__(y) <==> x==y
 |
 |  __format__(...)
 |      S.__format__(format_spec) -> string
 |
 |      Return a formatted version of S as described by format_spec.
 |
 |  __ge__(...)
 |      x.__ge__(y) <==> x>=y
 |
 |  __getattribute__(...)
 |      x.__getattribute__('name') <==> x.name
 |
 |  __getitem__(...)
 |      x.__getitem__(y) <==> x[y]
 |
 |  __getnewargs__(...)
 |
 |  __getslice__(...)
 |      x.__getslice__(i, j) <==> x[i:j]
 |
 |      Use of negative indices is not supported.
 |
 |  __gt__(...)
 |      x.__gt__(y) <==> x>y
 |
 |  __hash__(...)
 |      x.__hash__() <==> hash(x)
 |
 |  __le__(...)
 |      x.__le__(y) <==> x<=y
 |
 |  __len__(...)
 |      x.__len__() <==> len(x)
 |
 |  __lt__(...)
 |      x.__lt__(y) <==> x<y
 |
 |  __mod__(...)
 |      x.__mod__(y) <==> x%y
 |
 |  __mul__(...)
 |      x.__mul__(n) <==> x*n
 |
 |  __ne__(...)
 |      x.__ne__(y) <==> x!=y
 |
 |  __repr__(...)
 |      x.__repr__() <==> repr(x)
 |
 |  __rmod__(...)
 |      x.__rmod__(y) <==> y%x
 |
 |  __rmul__(...)
 |      x.__rmul__(n) <==> n*x
 |
 |  __sizeof__(...)
 |      S.__sizeof__() -> size of S in memory, in bytes
 |
 |  __str__(...)
 |      x.__str__() <==> str(x)
 |
 |  capitalize(...)
 |      S.capitalize() -> string
 |
 |      Return a copy of the string S with only its first character
 |      capitalized.
 |
 |  center(...)
 |      S.center(width[, fillchar]) -> string
 |
 |      Return S centered in a string of length width. Padding is
 |      done using the specified fill character (default is a space)
 |
 |  count(...)
 |      S.count(sub[, start[, end]]) -> int
 |
 |      Return the number of non-overlapping occurrences of substring sub in
 |      string S[start:end].  Optional arguments start and end are interpreted
 |      as in slice notation.
 |
 |  decode(...)
 |      S.decode([encoding[,errors]]) -> object
 |
 |      Decodes S using the codec registered for encoding. encoding defaults
 |      to the default encoding. errors may be given to set a different error
 |      handling scheme. Default is 'strict' meaning that encoding errors raise
 |      a UnicodeDecodeError. Other possible values are 'ignore' and 'replace'
 |      as well as any other name registered with codecs.register_error that is
 |      able to handle UnicodeDecodeErrors.
 |
 |  encode(...)
 |      S.encode([encoding[,errors]]) -> object
 |
 |      Encodes S using the codec registered for encoding. encoding defaults
 |      to the default encoding. errors may be given to set a different error
 |      handling scheme. Default is 'strict' meaning that encoding errors raise
 |      a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and
 |      'xmlcharrefreplace' as well as any other name registered with
 |      codecs.register_error that is able to handle UnicodeEncodeErrors.
 |
 |  endswith(...)
 |      S.endswith(suffix[, start[, end]]) -> bool
 |
 |      Return True if S ends with the specified suffix, False otherwise.
 |      With optional start, test S beginning at that position.
 |      With optional end, stop comparing S at that position.
 |      suffix can also be a tuple of strings to try.
 |
 |  expandtabs(...)
 |      S.expandtabs([tabsize]) -> string
 |
 |      Return a copy of S where all tab characters are expanded using spaces.
 |      If tabsize is not given, a tab size of 8 characters is assumed.
 |
 |  find(...)
 |      S.find(sub [,start [,end]]) -> int
 |
 |      Return the lowest index in S where substring sub is found,
 |      such that sub is contained within S[start:end].  Optional
 |      arguments start and end are interpreted as in slice notation.
 |
 |      Return -1 on failure.
 |
 |  format(...)
 |      S.format(*args, **kwargs) -> string
 |
 |      Return a formatted version of S, using substitutions from args and kwargs.
 |      The substitutions are identified by braces ('{' and '}').
 |
 |  index(...)
 |      S.index(sub [,start [,end]]) -> int
 |
 |      Like S.find() but raise ValueError when the substring is not found.
 |
 |  isalnum(...)
 |      S.isalnum() -> bool
 |
 |      Return True if all characters in S are alphanumeric
 |      and there is at least one character in S, False otherwise.
 |
 |  isalpha(...)
 |      S.isalpha() -> bool
 |
 |      Return True if all characters in S are alphabetic
 |      and there is at least one character in S, False otherwise.
 |
 |  isdigit(...)
 |      S.isdigit() -> bool
 |
 |      Return True if all characters in S are digits
 |      and there is at least one character in S, False otherwise.
 |
 |  islower(...)
 |      S.islower() -> bool
 |
 |      Return True if all cased characters in S are lowercase and there is
 |      at least one cased character in S, False otherwise.
 |
 |  isspace(...)
 |      S.isspace() -> bool
 |
 |      Return True if all characters in S are whitespace
 |      and there is at least one character in S, False otherwise.
 |
 |  istitle(...)
 |      S.istitle() -> bool
 |
 |      Return True if S is a titlecased string and there is at least one
 |      character in S, i.e. uppercase characters may only follow uncased
 |      characters and lowercase characters only cased ones. Return False
 |      otherwise.
 |
 |  isupper(...)
 |      S.isupper() -> bool
 |
 |      Return True if all cased characters in S are uppercase and there is
 |      at least one cased character in S, False otherwise.
 |
 |  join(...)
 |      S.join(iterable) -> string
 |
 |      Return a string which is the concatenation of the strings in the
 |      iterable.  The separator between elements is S.
 |
 |  ljust(...)
 |      S.ljust(width[, fillchar]) -> string
 |
 |      Return S left-justified in a string of length width. Padding is
 |      done using the specified fill character (default is a space).
 |
 |  lower(...)
 |      S.lower() -> string
 |
 |      Return a copy of the string S converted to lowercase.
 |
 |  lstrip(...)
 |      S.lstrip([chars]) -> string or unicode
 |
 |      Return a copy of the string S with leading whitespace removed.
 |      If chars is given and not None, remove characters in chars instead.
 |      If chars is unicode, S will be converted to unicode before stripping
 |
 |  partition(...)
 |      S.partition(sep) -> (head, sep, tail)
 |
 |      Search for the separator sep in S, and return the part before it,
 |      the separator itself, and the part after it.  If the separator is not
 |      found, return S and two empty strings.
 |
 |  replace(...)
 |      S.replace(old, new[, count]) -> string
 |
 |      Return a copy of string S with all occurrences of substring
 |      old replaced by new.  If the optional argument count is
 |      given, only the first count occurrences are replaced.
 |
 |  rfind(...)
 |      S.rfind(sub [,start [,end]]) -> int
 |
 |      Return the highest index in S where substring sub is found,
 |      such that sub is contained within S[start:end].  Optional
 |      arguments start and end are interpreted as in slice notation.
 |
 |      Return -1 on failure.
 |
 |  rindex(...)
 |      S.rindex(sub [,start [,end]]) -> int
 |
 |      Like S.rfind() but raise ValueError when the substring is not found.
 |
 |  rjust(...)
 |      S.rjust(width[, fillchar]) -> string
 |
 |      Return S right-justified in a string of length width. Padding is
 |      done using the specified fill character (default is a space)
 |
 |  rpartition(...)
 |      S.rpartition(sep) -> (head, sep, tail)
 |
 |      Search for the separator sep in S, starting at the end of S, and return
 |      the part before it, the separator itself, and the part after it.  If the
 |      separator is not found, return two empty strings and S.
 |
 |  rsplit(...)
 |      S.rsplit([sep [,maxsplit]]) -> list of strings
 |
 |      Return a list of the words in the string S, using sep as the
 |      delimiter string, starting at the end of the string and working
 |      to the front.  If maxsplit is given, at most maxsplit splits are
 |      done. If sep is not specified or is None, any whitespace string
 |      is a separator.
 |
 |  rstrip(...)
 |      S.rstrip([chars]) -> string or unicode
 |
 |      Return a copy of the string S with trailing whitespace removed.
 |      If chars is given and not None, remove characters in chars instead.
 |      If chars is unicode, S will be converted to unicode before stripping
 |
 |  split(...)
 |      S.split([sep [,maxsplit]]) -> list of strings
 |
 |      Return a list of the words in the string S, using sep as the
 |      delimiter string.  If maxsplit is given, at most maxsplit
 |      splits are done. If sep is not specified or is None, any
 |      whitespace string is a separator and empty strings are removed
 |      from the result.
 |
 |  splitlines(...)
 |      S.splitlines(keepends=False) -> list of strings
 |
 |      Return a list of the lines in S, breaking at line boundaries.
 |      Line breaks are not included in the resulting list unless keepends
 |      is given and true.
 |
 |  startswith(...)
 |      S.startswith(prefix[, start[, end]]) -> bool
 |
 |      Return True if S starts with the specified prefix, False otherwise.
 |      With optional start, test S beginning at that position.
 |      With optional end, stop comparing S at that position.
 |      prefix can also be a tuple of strings to try.
 |
 |  strip(...)
 |      S.strip([chars]) -> string or unicode
 |
 |      Return a copy of the string S with leading and trailing
 |      whitespace removed.
 |      If chars is given and not None, remove characters in chars instead.
 |      If chars is unicode, S will be converted to unicode before stripping
 |
 |  swapcase(...)
 |      S.swapcase() -> string
 |
 |      Return a copy of the string S with uppercase characters
 |      converted to lowercase and vice versa.
 |
 |  title(...)
 |      S.title() -> string
 |
 |      Return a titlecased version of S, i.e. words start with uppercase
 |      characters, all remaining cased characters have lowercase.
 |
 |  translate(...)
 |      S.translate(table [,deletechars]) -> string
 |
 |      Return a copy of the string S, where all characters occurring
 |      in the optional argument deletechars are removed, and the
 |      remaining characters have been mapped through the given
 |      translation table, which must be a string of length 256 or None.
 |      If the table argument is None, no translation is applied and
 |      the operation simply removes the characters in deletechars.
 |
 |  upper(...)
 |      S.upper() -> string
 |
 |      Return a copy of the string S converted to uppercase.
 |
 |  zfill(...)
 |      S.zfill(width) -> string
 |
 |      Pad a numeric string S with zeros on the left, to fill a field
 |      of the specified width.  The string S is never truncated.
 |
 |  ----------------------------------------------------------------------
 |  Data and other attributes defined here:
 |
 |  __new__ = <built-in method __new__ of type object>
 |      T.__new__(S, ...) -> a new object with type S, a subtype of T

str对象内置方法

list

list, 任意对象的有序集合,可变,可以通过索引取值、切片。嵌套、迭代及原处修改,也可以用来做堆栈和队列(数组)

常用功能:

  • 增删改查
  • 切片
  • 迭代
  • 长度
  • 成员关系
  • 内置方法
class list(object)
 |  list() -> new empty list
 |  list(iterable) -> new list initialized from iterable's items
 |
 |  Methods defined here:
 |
 |  __add__(...)
 |      x.__add__(y) <==> x+y
 |
 |  __contains__(...)
 |      x.__contains__(y) <==> y in x
 |
 |  __delitem__(...)
 |      x.__delitem__(y) <==> del x[y]
 |
 |  __delslice__(...)
 |      x.__delslice__(i, j) <==> del x[i:j]
 |
 |      Use of negative indices is not supported.
 |
 |  __eq__(...)
 |      x.__eq__(y) <==> x==y
 |
 |  __ge__(...)
 |      x.__ge__(y) <==> x>=y
 |
 |  __getattribute__(...)
 |      x.__getattribute__('name') <==> x.name
 |
 |  __getitem__(...)
 |      x.__getitem__(y) <==> x[y]
 |
 |  __getslice__(...)
 |      x.__getslice__(i, j) <==> x[i:j]
 |
 |      Use of negative indices is not supported.
 |
 |  __gt__(...)
 |      x.__gt__(y) <==> x>y
 |
 |  __iadd__(...)
 |      x.__iadd__(y) <==> x+=y
 |
 |  __imul__(...)
 |      x.__imul__(y) <==> x*=y
 |
 |  __init__(...)
 |      x.__init__(...) initializes x; see help(type(x)) for signature
 |
 |  __iter__(...)
 |      x.__iter__() <==> iter(x)
 |
 |  __le__(...)
 |      x.__le__(y) <==> x<=y
 |
 |  __len__(...)
 |      x.__len__() <==> len(x)
 |
 |  __lt__(...)
 |      x.__lt__(y) <==> x<y
 |
 |  __mul__(...)
 |      x.__mul__(n) <==> x*n
 |
 |  __ne__(...)
 |      x.__ne__(y) <==> x!=y
 |
 |  __repr__(...)
 |      x.__repr__() <==> repr(x)
 |
 |  __reversed__(...)
 |      L.__reversed__() -- return a reverse iterator over the list
 |
 |  __rmul__(...)
 |      x.__rmul__(n) <==> n*x
 |
 |  __setitem__(...)
 |      x.__setitem__(i, y) <==> x[i]=y
 |
 |  __setslice__(...)
 |      x.__setslice__(i, j, y) <==> x[i:j]=y
 |
 |      Use  of negative indices is not supported.
 |
 |  __sizeof__(...)
 |      L.__sizeof__() -- size of L in memory, in bytes
 |
 |  append(...)
 |      L.append(object) -- append object to end
 |
 |  count(...)
 |      L.count(value) -> integer -- return number of occurrences of value
 |
 |  extend(...)
 |      L.extend(iterable) -- extend list by appending elements from the iterable
 |
 |  index(...)
 |      L.index(value, [start, [stop]]) -> integer -- return first index of value.
 |      Raises ValueError if the value is not present.
 |
 |  insert(...)
 |      L.insert(index, object) -- insert object before index
 |
 |  pop(...)
 |      L.pop([index]) -> item -- remove and return item at index (default last).
 |      Raises IndexError if list is empty or index is out of range.
 |
 |  remove(...)
 |      L.remove(value) -- remove first occurrence of value.
 |      Raises ValueError if the value is not present.
 |
 |  reverse(...)
 |      L.reverse() -- reverse *IN PLACE*
 |
 |  sort(...)
 |      L.sort(cmp=None, key=None, reverse=False) -- stable sort *IN PLACE*;
 |      cmp(x, y) -> -1, 0, 1
 |
 |  ----------------------------------------------------------------------
 |  Data and other attributes defined here:
 |
 |  __hash__ = None
 |
 |  __new__ = <built-in method __new__ of type object>
 |      T.__new__(S, ...) -> a new object with type S, a subtype of T

list对象方法

tuple

tuple 任意对象的有序集合,不可变的对象,通过索引取值、切片与迭代.可以嵌套,可以说是只读的列表

常用功能:

  • 切片
  • 迭代
  • 成员关系
  • 内置方法
class tuple(object)
 |  tuple() -> empty tuple
 |  tuple(iterable) -> tuple initialized from iterable's items
 |
 |  If the argument is a tuple, the return value is the same object.
 |
 |  Methods defined here:
 |
 |  __add__(...)
 |      x.__add__(y) <==> x+y
 |
 |  __contains__(...)
 |      x.__contains__(y) <==> y in x
 |
 |  __eq__(...)
 |      x.__eq__(y) <==> x==y
 |
 |  __ge__(...)
 |      x.__ge__(y) <==> x>=y
 |
 |  __getattribute__(...)
 |      x.__getattribute__('name') <==> x.name
 |
 |  __getitem__(...)
 |      x.__getitem__(y) <==> x[y]
 |
 |  __getnewargs__(...)
 |
 |  __getslice__(...)
 |      x.__getslice__(i, j) <==> x[i:j]
 |
 |      Use of negative indices is not supported.
 |
 |  __gt__(...)
 |      x.__gt__(y) <==> x>y
 |
 |  __hash__(...)
 |      x.__hash__() <==> hash(x)
 |
 |  __iter__(...)
 |      x.__iter__() <==> iter(x)
 |
 |  __le__(...)
 |      x.__le__(y) <==> x<=y
 |
 |  __len__(...)
 |      x.__len__() <==> len(x)
 |
 |  __lt__(...)
 |      x.__lt__(y) <==> x<y
 |
 |  __mul__(...)
 |      x.__mul__(n) <==> x*n
 |
 |  __ne__(...)
 |      x.__ne__(y) <==> x!=y
 |
 |  __repr__(...)
 |      x.__repr__() <==> repr(x)
 |
 |  __rmul__(...)
 |      x.__rmul__(n) <==> n*x
 |
 |  count(...)
 |      T.count(value) -> integer -- return number of occurrences of value
 |
 |  index(...)
 |      T.index(value, [start, [stop]]) -> integer -- return first index of value.
 |      Raises ValueError if the value is not present.
 |
 |  ----------------------------------------------------------------------
 |  Data and other attributes defined here:
 |
 |  __new__ = <built-in method __new__ of type object>
 |      T.__new__(S, ...) -> a new object with type S, a subtype of T

tuple对象的内置方法

dict

dict 任意对象的无序集合,可变,映射类型,通过key-value(键值)储存和取值,支持原处修改. 字典中的key是唯一并且是不重复的对象,而且只能使用不可变的对象作为key
常用功能:

  • 增删改查
  • 迭代
  • 成员判断
  • 内置方法
  • 成员关系
class dict(object)
 |  dict() -> new empty dictionary
 |  dict(mapping) -> new dictionary initialized from a mapping object's
 |      (key, value) pairs
 |  dict(iterable) -> new dictionary initialized as if via:
 |      d = {}
 |      for k, v in iterable:
 |          d[k] = v
 |  dict(**kwargs) -> new dictionary initialized with the name=value pairs
 |      in the keyword argument list.  For example:  dict(one=1, two=2)
 |
 |  Methods defined here:
 |
 |  __cmp__(...)
 |      x.__cmp__(y) <==> cmp(x,y)
 |
 |  __contains__(...)
 |      D.__contains__(k) -> True if D has a key k, else False
 |
 |  __delitem__(...)
 |      x.__delitem__(y) <==> del x[y]
 |
 |  __eq__(...)
 |      x.__eq__(y) <==> x==y
 |
 |  __ge__(...)
 |      x.__ge__(y) <==> x>=y
 |
 |  __getattribute__(...)
 |      x.__getattribute__('name') <==> x.name
 |
 |  __getitem__(...)
 |      x.__getitem__(y) <==> x[y]
 |
 |  __gt__(...)
 |      x.__gt__(y) <==> x>y
 |
 |  __init__(...)
 |      x.__init__(...) initializes x; see help(type(x)) for signature
 |
 |  __iter__(...)
 |      x.__iter__() <==> iter(x)
 |
 |  __le__(...)
 |      x.__le__(y) <==> x<=y
 |
 |  __len__(...)
 |      x.__len__() <==> len(x)
 |
 |  __lt__(...)
 |      x.__lt__(y) <==> x<y
 |
 |  __ne__(...)
 |      x.__ne__(y) <==> x!=y
 |
 |  __repr__(...)
 |      x.__repr__() <==> repr(x)
 |
 |  __setitem__(...)
 |      x.__setitem__(i, y) <==> x[i]=y
 |
 |  __sizeof__(...)
 |      D.__sizeof__() -> size of D in memory, in bytes
 |
 |  clear(...)
 |      D.clear() -> None.  Remove all items from D.
 |
 |  copy(...)
 |      D.copy() -> a shallow copy of D
 |
 |  fromkeys(...)
 |      dict.fromkeys(S[,v]) -> New dict with keys from S and values equal to v.
 |      v defaults to None.
 |
 |  get(...)
 |      D.get(k[,d]) -> D[k] if k in D, else d.  d defaults to None.
 |
 |  has_key(...)
 |      D.has_key(k) -> True if D has a key k, else False
 |
 |  items(...)
 |      D.items() -> list of D's (key, value) pairs, as 2-tuples
 |
 |  iteritems(...)
 |      D.iteritems() -> an iterator over the (key, value) items of D
 |
 |  iterkeys(...)
 |      D.iterkeys() -> an iterator over the keys of D
 |
 |  itervalues(...)
 |      D.itervalues() -> an iterator over the values of D
 |
 |  keys(...)
 |      D.keys() -> list of D's keys
 |
 |  pop(...)
 |      D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
 |      If key is not found, d is returned if given, otherwise KeyError is raised
 |
 |  popitem(...)
 |      D.popitem() -> (k, v), remove and return some (key, value) pair as a
 |      2-tuple; but raise KeyError if D is empty.
 |
 |  setdefault(...)
 |      D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D
 |
 |  update(...)
 |      D.update([E, ]**F) -> None.  Update D from dict/iterable E and F.
 |      If E present and has a .keys() method, does:     for k in E: D[k] = E[k]
 |      If E present and lacks .keys() method, does:     for (k, v) in E: D[k] = v
 |      In either case, this is followed by: for k in F: D[k] = F[k]
 |
 |  values(...)
 |      D.values() -> list of D's values
 |
 |  viewitems(...)
 |      D.viewitems() -> a set-like object providing a view on D's items
 |
 |  viewkeys(...)
 |      D.viewkeys() -> a set-like object providing a view on D's keys
 |
 |  viewvalues(...)
 |      D.viewvalues() -> an object providing a view on D's values
 |
 |  ----------------------------------------------------------------------
 |  Data and other attributes defined here:
 |
 |  __hash__ = None
 |
 |  __new__ = <built-in method __new__ of type object>
 |      T.__new__(S, ...) -> a new object with type S, a subtype of T

dict对象的内置方法

set

set 集合是无序不重复的对象,常用来消除重复、成员关系判断及数学上的交集、差集

常用功能:

  • 去重
  • 成员关系
  • 交集、差集
  • 内置方法
class set(object)
 |  set() -> new empty set object
 |  set(iterable) -> new set object
 |
 |  Build an unordered collection of unique elements.
 |
 |  Methods defined here:
 |
 |  __and__(...)
 |      x.__and__(y) <==> x&y
 |
 |  __cmp__(...)
 |      x.__cmp__(y) <==> cmp(x,y)
 |
 |  __contains__(...)
 |      x.__contains__(y) <==> y in x.
 |
 |  __eq__(...)
 |      x.__eq__(y) <==> x==y
 |
 |  __ge__(...)
 |      x.__ge__(y) <==> x>=y
 |
 |  __getattribute__(...)
 |      x.__getattribute__('name') <==> x.name
 |
 |  __gt__(...)
 |      x.__gt__(y) <==> x>y
 |
 |  __iand__(...)
 |      x.__iand__(y) <==> x&=y
 |
 |  __init__(...)
 |      x.__init__(...) initializes x; see help(type(x)) for signature
 |
 |  __ior__(...)
 |      x.__ior__(y) <==> x|=y
 |
 |  __isub__(...)
 |      x.__isub__(y) <==> x-=y
 |
 |  __iter__(...)
 |      x.__iter__() <==> iter(x)
 |
 |  __ixor__(...)
 |      x.__ixor__(y) <==> x^=y
 |
 |  __le__(...)
 |      x.__le__(y) <==> x<=y
 |
 |  __len__(...)
 |      x.__len__() <==> len(x)
 |
 |  __lt__(...)
 |      x.__lt__(y) <==> x<y
 |
 |  __ne__(...)
 |      x.__ne__(y) <==> x!=y
 |
 |  __or__(...)
 |      x.__or__(y) <==> x|y
 |
 |  __rand__(...)
 |      x.__rand__(y) <==> y&x
 |
 |  __reduce__(...)
 |      Return state information for pickling.
 |
 |  __repr__(...)
 |      x.__repr__() <==> repr(x)
 |
 |  __ror__(...)
 |      x.__ror__(y) <==> y|x
 |
 |  __rsub__(...)
 |      x.__rsub__(y) <==> y-x
 |
 |  __rxor__(...)
 |      x.__rxor__(y) <==> y^x
 |
 |  __sizeof__(...)
 |      S.__sizeof__() -> size of S in memory, in bytes
 |
 |  __sub__(...)
 |      x.__sub__(y) <==> x-y
 |
 |  __xor__(...)
 |      x.__xor__(y) <==> x^y
 |
 |  add(...)
 |      Add an element to a set.
 |
 |      This has no effect if the element is already present.
 |
 |  clear(...)
 |      Remove all elements from this set.
 |
 |  copy(...)
 |      Return a shallow copy of a set.
 |
 |  difference(...)
 |      Return the difference of two or more sets as a new set.
 |
 |      (i.e. all elements that are in this set but not the others.)
 |
 |  difference_update(...)
 |      Remove all elements of another set from this set.
 |
 |  discard(...)
 |      Remove an element from a set if it is a member.
 |
 |      If the element is not a member, do nothing.
 |
 |  intersection(...)
 |      Return the intersection of two or more sets as a new set.
 |
 |      (i.e. elements that are common to all of the sets.)
 |
 |  intersection_update(...)
 |      Update a set with the intersection of itself and another.
 |
 |  isdisjoint(...)
 |      Return True if two sets have a null intersection.
 |
 |  issubset(...)
 |      Report whether another set contains this set.
 |
 |  issuperset(...)
 |      Report whether this set contains another set.
 |
 |  pop(...)
 |      Remove and return an arbitrary set element.
 |      Raises KeyError if the set is empty.
 |
 |  remove(...)
 |      Remove an element from a set; it must be a member.
 |
 |      If the element is not a member, raise a KeyError.
 |
 |  symmetric_difference(...)
 |      Return the symmetric difference of two sets as a new set.
 |
 |      (i.e. all elements that are in exactly one of the sets.)
 |
 |  symmetric_difference_update(...)
 |      Update a set with the symmetric difference of itself and another.
 |
 |  union(...)
 |      Return the union of sets as a new set.
 |
 |      (i.e. all elements that are in either set.)
 |
 |  update(...)
 |      Update a set with the union of itself and others.
 |
 |  ----------------------------------------------------------------------
 |  Data and other attributes defined here:
 |
 |  __hash__ = None
 |
 |  __new__ = <built-in method __new__ of type object>
 |      T.__new__(S, ...) -> a new object with type S, a subtype of T

set对象的内置方法

bool

bool 布尔类型是int的子类, 就是True(0)、False(1)

class bool(int)
 |  bool(x) -> bool
 |
 |  Returns True when the argument x is true, False otherwise.
 |  The builtins True and False are the only two instances of the class bool.
 |  The class bool is a subclass of the class int, and cannot be subclassed.
 |
 |  Method resolution order:
 |      bool
 |      int
 |      object
 |
 |  Methods defined here:
 |
 |  __and__(...)
 |      x.__and__(y) <==> x&y
 |
 |  __or__(...)
 |      x.__or__(y) <==> x|y
 |
 |  __rand__(...)
 |      x.__rand__(y) <==> y&x
 |
 |  __repr__(...)
 |      x.__repr__() <==> repr(x)
 |
 |  __ror__(...)
 |      x.__ror__(y) <==> y|x
 |
 |  __rxor__(...)
 |      x.__rxor__(y) <==> y^x
 |
 |  __str__(...)
 |      x.__str__() <==> str(x)
 |
 |  __xor__(...)
 |      x.__xor__(y) <==> x^y
 |
 |  ----------------------------------------------------------------------
 |  Data and other attributes defined here:
 |
 |  __new__ = <built-in method __new__ of type object>
 |      T.__new__(S, ...) -> a new object with type S, a subtype of T
 |
 |  ----------------------------------------------------------------------
 |  Methods inherited from int:
 |
 |  __abs__(...)
 |      x.__abs__() <==> abs(x)
 |
 |  __add__(...)
 |      x.__add__(y) <==> x+y
 |
 |  __cmp__(...)
 |      x.__cmp__(y) <==> cmp(x,y)
 |
 |  __coerce__(...)
 |      x.__coerce__(y) <==> coerce(x, y)
 |
 |  __div__(...)
 |      x.__div__(y) <==> x/y
 |
 |  __divmod__(...)
 |      x.__divmod__(y) <==> divmod(x, y)
 |
 |  __float__(...)
 |      x.__float__() <==> float(x)
 |
 |  __floordiv__(...)
 |      x.__floordiv__(y) <==> x//y
 |
 |  __format__(...)
 |
 |  __getattribute__(...)
 |      x.__getattribute__('name') <==> x.name
 |
 |  __getnewargs__(...)
 |
 |  __hash__(...)
 |      x.__hash__() <==> hash(x)
 |
 |  __hex__(...)
 |      x.__hex__() <==> hex(x)
 |
 |  __index__(...)
 |      x[y:z] <==> x[y.__index__():z.__index__()]
 |
 |  __int__(...)
 |      x.__int__() <==> int(x)
 |
 |  __invert__(...)
 |      x.__invert__() <==> ~x
 |
 |  __long__(...)
 |      x.__long__() <==> long(x)
 |
 |  __lshift__(...)
 |      x.__lshift__(y) <==> x<<y
 |
 |  __mod__(...)
 |      x.__mod__(y) <==> x%y
 |
 |  __mul__(...)
 |      x.__mul__(y) <==> x*y
 |
 |  __neg__(...)
 |      x.__neg__() <==> -x
 |
 |  __nonzero__(...)
 |      x.__nonzero__() <==> x != 0
 |
 |  __oct__(...)
 |      x.__oct__() <==> oct(x)
 |
 |  __pos__(...)
 |      x.__pos__() <==> +x
 |
 |  __pow__(...)
 |      x.__pow__(y[, z]) <==> pow(x, y[, z])
 |
 |  __radd__(...)
 |      x.__radd__(y) <==> y+x
 |
 |  __rdiv__(...)
 |      x.__rdiv__(y) <==> y/x
 |
 |  __rdivmod__(...)
 |      x.__rdivmod__(y) <==> divmod(y, x)
 |
 |  __rfloordiv__(...)
 |      x.__rfloordiv__(y) <==> y//x
 |
 |  __rlshift__(...)
 |      x.__rlshift__(y) <==> y<<x
 |
 |  __rmod__(...)
 |      x.__rmod__(y) <==> y%x
 |
 |  __rmul__(...)
 |      x.__rmul__(y) <==> y*x
 |
 |  __rpow__(...)
 |      y.__rpow__(x[, z]) <==> pow(x, y[, z])
 |
 |  __rrshift__(...)
 |      x.__rrshift__(y) <==> y>>x
 |
 |  __rshift__(...)
 |      x.__rshift__(y) <==> x>>y
 |
 |  __rsub__(...)
 |      x.__rsub__(y) <==> y-x
 |
 |  __rtruediv__(...)
 |      x.__rtruediv__(y) <==> y/x
 |
 |  __sub__(...)
 |      x.__sub__(y) <==> x-y
 |
 |  __truediv__(...)
 |      x.__truediv__(y) <==> x/y
 |
 |  __trunc__(...)
 |      Truncating an Integral returns itself.
 |
 |  bit_length(...)
 |      int.bit_length() -> int
 |
 |      Number of bits necessary to represent self in binary.
 |      >>> bin(37)
 |      '0b100101'
 |      >>> (37).bit_length()
 |      6
 |
 |  conjugate(...)
 |      Returns self, the complex conjugate of any int.
 |
 |  ----------------------------------------------------------------------
 |  Data descriptors inherited from int:
 |
 |  denominator
 |      the denominator of a rational number in lowest terms
 |
 |  imag
 |      the imaginary part of a complex number
 |
 |  numerator
 |      the numerator of a rational number in lowest terms
 |
 |  real
 |      the real part of a complex number

bool对象的内置方法

None

空对象,不等同于0

三、流程控制

主要是:

  • if/elif/else、三元表达式
  • while、for循环
  • contiune、break、else、pass

if/elif/else

if语句,如果条件为True执行所属的代码块,可以嵌套,没什么好说的

if 语句:
    代码块   

elif 语句:
    代码块
...
else:
    代码块   

三元表达式(真左假右)

三元表达式是if/else的简化版,通常四行的代码可以写成一行,有什么用呢? 精简代码但作用有限

if 1 + 1 == 2:
  reslut = Ture
else:
  reslut False

用三元表表达式简写

reslut = True if 1 + 1 == 2 else False

while、for循环

for循环是一个通用的序列迭代器,可以遍历任何有序对象内的元素并对每个元素运行一个代码块. for是强制迭代直到抛出异常 (内部已处理异常)

>>> for p in 'python':
...     print p
p
y
t
h
o
n

for循环有时候也是一种解包(unpack)

data = {'name':'weimin','age':20}

for k,v in data.items():        #key与values对应
    print k,v

while 条件循环,条件为真则循环执行代码块直到条件为假退出循环,为了避免死循环应该给出循环退出的条件, 除非做守护进程

i = 1
BOOL = True
while BOOL:
	print 'Hello boy\t{0}'.format(i)
	i += 1
	if i > 200:
	  BOOL=False

//for比while好写,尽量使用for

break、contiune、else、pass

  • contiune  跳出当前的循环,开始下一次循环
  • break     停止当前所在循环
  • else      对于for和while, 是循环正常完成后才执行else下的语句
  • pass      占位符,什么也不干

四、运算符

就是两个对象进行运算

算术运算符  + 、- 、* 、/、 %、// 、**
比较运算符  ==、 >=、<= 、> 、<、!=
赋值运算符  =、+=、-=、*=、/=、**=、%= 、//=
逻辑运算符  and、or、not
位运算符   
成员运算符  in、not in
身份运算符  is、is not

== 是比较值相等,  is是比较两个对象是否同一个地址

五、真值测试、短路计算

  • 非数字零和非空对象、None都为Fasle,其它对象为True
  • 比较和相等测试会返回True或False
  • 布尔and和or、not运算符会返回真或假
>>> bool(0)         #数字0是False
False
>>> bool([])        #空列表是False
False
>>> bool(None)      #None对是Fasle
False

比较测试返回bool值

>>> 1 == 1
True
>>> 1 > 2
False

and、or、not测试

>>> not number
False
>>> number = 10
>>> nmuber < 20 and nmuber > 10
>>> number <= 20
True

短路计算

  • or:  真or真、假or假、真or假 、假or真 (只要一个为真即可,所以第一个为真则返回True,如果第一个为假则返回第二个)
  • and:  真 and 真、假and假 、真and假、假or真 (必须两个都为真,如果第一个为假则直接返回第一个假,如果第一个为真则返回第二个)
>>> 1 or 2      #为什么是1, 对于or只要有一个为True则为True,第一个数字1为True则不往后面判断
1
>>> 0 or 1      #为什么是1, 对于or只要有一个为True则为True,第一个数字0为Fasle所以往后面判断
1
>>> 0 and 1     #为什么是0, 对于and必须两个结果对象为True则为True,第一个数字0为False则不往后面判断
0
>>> 1 and 2     #为什么是2, 对于and必须两个结果对象为True则为True,第一个数字1为True还需往后面判断
2

短路计算赋值:

>>> user = 0 or 1
>>> user
1
>>> user = 0 and 1
>>> user
0

总结:

  • Python的数据类型,可变与不可变、序列型、有序和无序、迭代,每种数据类型可以看出一个类,提供了对象的属性和方法
  • 流程控制,if语句与循环、三元表达式(真左假右)
  • 真值测试、短路计算的过程