天天看點

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]]           

歡迎各位同學一起來交流學習心得!