零基础Python学习笔记001(数字类型和布尔类型)

1. 数字类型

  • 整数:Python 的整数长度不受限制,有无限大的精度。

  • 浮点数

print(0.1 + 0.2)  # 0.30000000000000004

i = 0
while i < 1:
    i += 0.1
    print(i)
'''
0.1
0.2
0.30000000000000004
0.4
0.5
0.6
0.7
0.7999999999999999
0.8999999999999999
0.9999999999999999
1.0999999999999999
'''

Python的浮点数具有误差的原因,是因为Python采用IEEE754标准来存放浮点数,会产生一定精度上的误差。

但是由于误差的存在,也会带来很多问题:

print(0.3 == 0.1 + 0.2)  # False

为了解决浮点数精度不够的问题,可以引入decimal模块:

import decimal as dec
a = dec.Decimal("0.1")
b = dec.Decimal("0.2")
print(a + b)  # 0.3
c = dec.Decimal("0.3")
print(a + b == c)  # True

科学计数法

print(0.00005)  # 5e-05
print(0.0000018)  # 1.8e-06
  • 复数
x = 8 + 10j
print(x.real)  # 获得实部 8.0
print(x.imag)  # 获得虚部 10.0
  • 数字之间的运算
操作结果
x + y求和
x - y求差
x * y求积
x / y求商
x // y求地板商
x % y求余数
- xx的相反数
+ xx本身
abs(x)求x 的绝对值
int(x)将x强制转换为整数
float(x)将x强制转换为浮点数
complex(real, imag)返回一个复数,real是实部,imag是虚部
divmod(x, y)求(x // y,x % y)
pow(x, y)求x 的y 次方
x ** y求x 的y 次方
print(3 / 2)  # 1.5
print(3 // 2)  # 1
print(-3 // 2)  # -2
print(3 % 2)  # 1
print(abs(-5))  # 5
print(int(1.25))  # 1
print(float(1))  # 1.0
print(complex(1, 2))  # 1 + 2i
print(divmod(6, 5))  # 1 1
print(2, 3)  # 8
print(2 ** 3)  # 8

2. 布尔类型

import decimal
from mpmath import fraction

# 以下情况布尔值均为False
# 定义为False的对象
print(bool(None))
print(bool(False))

# 值为0的数字类型
print(bool(0))
print(bool(0.0))
print(bool(0j))
print(bool(Decimal(0)))
print(bool(Fraction(0, 1)))

# 空的序列和集合
print(bool(''))
print(bool(()))
print(bool([]))
print(bool({}))
print(bool(set()))
print(bool(range()))

布尔类型就是特殊的整数类型

print(True == 1)  # True
print(False ==0)  # False

print(True + False)
print(True - False)
print(True * False)
print(False / True)
'''
1
1
0
0.0
'''
  • 逻辑运算符 and,or,not
print(True and False)  # False
print(True or False)  # True
print(not True)  # False
print(not False)  # True

Python中的任何对象都能直接进行真值测试,用于if或着while语句的条件判断,也可以作为布尔逻辑运算符的操作数。

短路逻辑的核心思想:从左往右,只有当第一个操作数的值无法确定逻辑运算的结果时,才对第二个操作数进行求值。

print((not 1) or (0 and 1) or (3 and 4) or (5 and 6) or (7 and 8 and 9))  # 4
print(not 1 or 0 and 1 or 3 and 4 or 5 and 6 or 7 and 8 and 9)  # 4
  • 运算符优先级
优先级运算符描述
1lambdaLambda表达式
2if - else条件表达式
3or布尔 或
4and布尔 与
5not布尔 非
6in, not in, is, is not, <, <=, >, >=, !=, ==成员测试,同一性测试,比较
7|按位 或
8^按位 异或
9&按位 与
10<<, >>移位
11+, -加法,减法
12*, @, /, //, %乘法,矩阵乘法,除法,地板除,取余数
13+x, -x, ~x正号,负号,按位翻转
14**指数
15await xAwait表达式
16x[index], x[index index], x[arguments…], x.attribute下标,切片,函数调用,属性引用
17(expressions…), [expressions…], {key:value…}, {expression…}绑定或元组显示,列表显示,字典显示,集合显示

欢迎私信交流(师从小甲鱼)

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Network_Engineer

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值