python变量,运算符,数据类型与位运算

查漏补缺

  1. 保留小数后n位
import decimal
a = decimal.getcontext()
print(a)

# Context(prec=28, rounding=ROUND_HALF_EVEN, Emin=-999999, Emax=999999,
# capitals=1, clamp=0, flags=[], 
# traps=[InvalidOperation, DivisionByZero, Overflow])
b = Decimal(1) / Decimal(3)
print(b)
# 0.3333333333333333333333333333
  1. 用 getcontext().prec 来调整精度
decimal.getcontext().prec = 4
c = Decimal(1) / Decimal(3)
print(c)
# 0.3333
  1. bool 作用在容器类型变量:X 只要不是空的变量,bool(X) 就是 True,其余就是 False
print(type(''), bool(''), bool('python'))
# <class 'str'> False True

print(type(()), bool(()), bool((10,)))
# <class 'tuple'> False True

print(type([]), bool([]), bool([1, 2]))
# <class 'list'> False True

print(type({}), bool({}), bool({'a': 1, 'b': 2}))
# <class 'dict'> False True

print(type(set()), bool(set()), bool({1, 2}))
# <class 'set'> False True
  1. 获取类型信息 isinstance(object, classinfo)
print(isinstance(1, int))  # True
print(isinstance(5.2, float))  # True
print(isinstance(True, bool))  # True
print(isinstance('5.2', str))  # True

练习题

  1. 怎样对python中的代码进行注释?
    #表示注释,作用于整行
    ‘’’ ‘’’ 或者 “”" “”"表示区间注释,在三引号之间的所有内容被注释
  2. python有哪些运算符,这些运算符的优先级是怎样的?

在这里插入图片描述

  • 一元运算符优于二元运算符。例如3 ** -2等价于3 ** (-2)。
  • 先算术运算,后移位运算,最后位运算。例如 1 << 3 + 2 & 7等价于 1 << (3 + 2)) & 7。
  • 逻辑运算最后结合。例如3 < 4 and 4 < 5等价于(3 < 4) and (4 < 5)。
  1. python 中 is, is not 与 ==, != 的区别是什么?
  • is, is not 对比的是两个变量的内存地址
  • ==, != 对比的是两个变量的值
  • 比较的两个变量,指向的都是地址不可变的类型(str等),那么is,is not 和 ==,!= 是完全等价的。
  • 对比的两个变量,指向的是地址可变的类型(list,dict,tuple等),则两者是有区别的
  1. python 中包含哪些数据类型?这些数据类型之间如何转换?
  • 包括 int, float, bool 类型
  • 转换为整型 int(x, base=10)
  • 转换为字符串 str(object=’’)
  • 转换为浮点型 float(x)

位运算


版权声明:本文为weixin_46167028原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。