Python训练营笔记 从变量到异常处理 Day2

天池龙珠计划 Python训练营

所记录的知识点

  1. is ==
  2. 变量名
  3. Decimal对象的默认精度
  4. isinstance
  5. 判断整数是否在指定区间范围内
  6. 列表推导式

1、is ==

is 比较内存地址
== 比较值
In [1]: a = ["hello"]

In [2]: b=["hello"]

In [3]: id(a),id(b)
Out[3]: (1493364865416, 1493364989768)

In [4]: help(id)
Help on built-in function id in module builtins:

id(obj, /)
    Return the identity of an object.

    This is guaranteed to be unique among simultaneously existing objects.
    (CPython uses the object's memory address.)


In [5]: a is b  # memory address
Out[5]: False

In [6]: a == b  # value
Out[6]: True

In [7]: exit

2、变量名

变量名是大小写敏感的
In [1]: abc = 12

In [2]: aBc = 222

In [3]: abc
Out[3]: 12

In [4]: aBc
Out[4]: 222

In [5]: exit

3、Decimal对象的默认精度

decimal.getcontext
In [1]: import decimal

In [2]: decimal.getcontext()
Out[2]: Context(prec=28, rounding=ROUND_HALF_EVEN, Emin=-999999, Emax=999999, capitals=1, clamp=0, flags=[], traps=[InvalidOperation, DivisionByZero, Overflow])

In [3]: decimal.getcontext().prec
Out[3]: 28

4、isinstance

isinstance 会考虑继承关系,认为 子类是一种父类类型
In [1]: class Animal:
   ...:     pass
   ...:

In [2]: class Dog(Animal):
   ...:     pass
   ...:

In [3]: isinstance(Dog(),Animal)
Out[3]: True

In [4]: isinstance(Animal(),Dog)
Out[4]: False

In [5]: help(isinstance)
Help on built-in function isinstance in module builtins:

isinstance(obj, class_or_tuple, /)
    Return whether an object is an instance of a class or of a subclass thereof.

    A tuple, as in ``isinstance(x, (A, B, ...))``, may be given as the target to
    check against. This is equivalent to ``isinstance(x, A) or isinstance(x, B)
    or ...`` etc.

5、判断整数是否在指定区间范围内

a 是否在 [3,5)内
In [1]: a = 4

In [2]: 3<= a <5
Out[2]: True

In [3]: a = 3

In [4]: 3<= a <5
Out[4]: True

In [5]: a=5

In [6]: 3<= a <5
Out[6]: False

In [7]: a = "h"

In [8]: 3<= a <5
-----------------------------------------------------------------------
TypeError                             Traceback (most recent call last)
<ipython-input-8-78a4d661f5d1> in <module>
----> 1 3<= a <5

TypeError: '<=' not supported between instances of 'int' and 'str'

In [9]:

6、列表推导式

In [1]: [ [i,j] for i in [1,3,5,7] if i != 3 for j in [2,4,6,8]]
   ...:
Out[1]:
[[1, 2],
 [1, 4],
 [1, 6],
 [1, 8],
 [5, 2],
 [5, 4],
 [5, 6],
 [5, 8],
 [7, 2],
 [7, 4],
 [7, 6],
 [7, 8]]

In [2]: [ [i,j*2] for i in [1,3,5,7] if i != 3 for j in [2,4,6,8
   ...: ]]
Out[2]:
[[1, 4],
 [1, 8],
 [1, 12],
 [1, 16],
 [5, 4],
 [5, 8],
 [5, 12],
 [5, 16],
 [7, 4],
 [7, 8],
 [7, 12],
 [7, 16]]


欢迎各位同学一起来交流学习心得!

上一篇:关于bootstrap下拉框组件点击后不自动关闭的处理


下一篇:设计模式之使用Enum来实现strategy(策略模式系列2)