S1-变量与数据类型


这个系列主要是python入门系列;入门系列可能还是主推廖雪峰老师和菜鸟教程的文字教程。

  • 这节课主要是学习变量、运算符与数据类型。

1 变量、运算符与数据类型

1.1 注释

  • 表示单行注释,作用整行。与//作用相当。在jupyter notebook中,# %% 表示分段,达成分模块作用。

# 这是一个注释
print("Hello world")

  • ‘’’ ‘’’ 或者 “”" “”" 表示区间注释,在三引号之间的所有内容被注释
    【例】多行注释
'''
这是多行注释,用三个单引号
这是多行注释,用三个单引号
这是多行注释,用三个单引号
'''
print("Hello china") 

1.2 运算符

  • 对于运算符,不要记住运算先后顺序,为了方便别人和自己,不确定先后先后顺序的就使用小括号。
  • 运算符也是关键字。

1.2.1 算术运算符

操作符 名称 示例

  • 加 1 + 1
  • 减 2 - 1
  • 乘 3 * 4
    / 除 3 / 4
    // 整除(地板除) 3 // 4
    % 取余 3 % 4
    ** 幂 2 ** 3
    【例】
print(1 + 1)  # 2
print(2 - 1)  # 1
print(3 * 4)  # 12
print(3 / 4)  # 0.75
print(3 // 4)  # 0
print(3 % 4)  # 3
print(2 ** 3)  # 8

1.2.2 比较运算符–结果是逻辑量

比较运算符产生的结果是逻辑量–true or false.
操作符 名称 示例

大于 2 > 1
= 大于等于 2 >= 4
< 小于 1 < 2
<= 小于等于 5 <= 2
== 等于 3 == 4
!= 不等于 3 != 5
【例子】

print(2 > 1)  # True
print(2 >= 4)  # False
print(1 < 2)  # True
print(5 <= 2)  # False
print(3 == 4)  # False
print(3 != 5)  # True

1.2.3 逻辑运算符

这就是逻辑运算,处理思路:写逻辑真值表和
操作符 名称 示例
and 与 (3 > 2) and (3 < 5)
or 或 (1 > 3) or (9 < 2)
not 非 not (2 > 1)
【例子】

# 一定要注意括号啊
print((3 > 2) and (3 < 5))  # True
print((1 > 3) or (9 < 2))  # False
print(not (2 > 1))  # False

1.2.4 位运算符

当初学C语言的时候,我就常常把C语言中的为运算符合逻辑运算符搞混,因为在C语言中,他们的运算符也很相像。

  • 作用:就像它的名字一样,用来处理二进制下的数,按位运算。在C语言中,常用来控制单片机。
操作符 名称 示例
按位取反 ~4
& 按位与 4 & 5
| 按位或 4 | 5
^ 按位异或 4 ^ 5
<< 左移 4 << 2

右移 4 >> 2
【例子】:有关二进制的运算,参见“位运算”部分的讲解。

print(bin(4))                  # 0b100
print(bin(5))                  # 0b101
print(bin(~4), ~4)          # -0b101 -5
print(bin(4 & 5), 4 & 5)  # 0b100 4
print(bin(4 | 5), 4 | 5)      # 0b101 5
print(bin(4 ^ 5), 4 ^ 5)   # 0b1 1
print(bin(4 << 2), 4 << 2)  # 0b10000 16
print(bin(4 >> 2), 4 >> 2)  # 0b1 1

1.2.5 三目运算符

这个运算操作符,以前经常碰到过。所以有时候自己可以不常使用,但是读别人的代码,可能会碰到。
【未用例子】

x, y = 4, 5
if x < y:
    small = x
else:
    small = y

print(small)  # 4

【使用之后】

x, y = 4, 5
small = x if x < y else y
print(small)  # 4

1.2.6 其他运算符—结果是逻辑量。

这些运算符在字典,数组等数据类型下的循环结构常用到。结果是逻辑量。
操作符 名称 示例
in 存在 ‘A’ in [‘A’, ‘B’, ‘C’]
not in 不存在 ‘h’ not in [‘A’, ‘B’, ‘C’]
is 是 “hello” is “hello”
is not 不是 “hello” is not “hello”
【in例子】

letters = ['A', 'B', 'C']   # 字符数组
if 'A' in letters:
    print('A' + ' exists')
if 'h' not in letters:
    print('h' + ' not exists')

# A exists
# h not exists

【is例子】

  • 比较的两个变量均指向不可变类型
a = "hello" # 常数,常量
b = "hello"
print(a is b, a == b)  # True True
print(a is not b, a != b)  # False False
  • 比较的两个变量均指向可变类型
    a = [“hello”] # 变量
    b = [“hello”]
    print(a is b, a == b) # False True
    print(a is not b, a != b) # True False
    【例子】比较的两个变量均指向可变类型
    ** 小结**:
  • is, is not 对比的是两个变量的内存地址;
  • ==, != 对比的是两个变量的值
  • 比较的两个变量,指向的都是地址不可变的类型(str等),那么is,is not 和 ==,!= 是完全等价的。
  • 对比的两个变量,指向的是地址可变的类型(list,dict,tuple等),则两者是有区别。
    运算符优先级的几个原则:
  1. 先算术运算,后移位运算,最后位运算。例如 1 << 3 + 2 & 7等价于 (1 << (3 + 2)) & 7。
  2. 逻辑运算最后结合。例如3 < 4 and 4 < 5等价于(3 < 4) and (4 < 5)。
  3. 一元运算符优于二元运算符。例如3 ** -2等价于3 ** (-2)。
  4. 自己写代码的时候不确定的就用小括号,与人为便。

1.3 变量与赋值

  • 不像C语言,先确定数据类型定义;python一切皆对象,变量赋值即生成。
  • 变量名包括字母,数字和下划线,但变量名不能以数字开头。【简洁就是美–钢琴】
  • python对变量名的大小写是敏感的。
# 【例子】
teacher='老马的程序人生'
print(teacher)  # 老马的程序人生
# 【例子】
first=2 
second=3
third=first+second
print(third)  # 5

# 【例子】
myTeacher=“老马的程序人生”
yourTeacher="小马的程序人生"
ourTeacher=myteacher+','+yourteacher
print(ourTeacher)  # 老马的程序人生,小马的程序人生

1.4 数据类型与转换

数据类型基本分为两大类:

  • 基本类型:数值型
  • 容器类型:字符串、元组、列表、字典和集合(很少用)

1.4.1 数值数据类型

类型 名称 示例
int 整型 <class ‘int’> -876, 10
float 浮点型<class ‘float’> 3.149, 11.11
bool 布尔型<class ‘bool’> True, False

  • 1.整型
    【例子】:通过 print() 可看出 a 的值,以及类 (class) 是int。
    ``python
    a = 1031
    print(a, type(a)) # 1031 <class ‘int’>

Python 里面万物皆对象(object),数据类型也不例外,只要是对象,就有相应的属性 (attributes) 和方法(methods)。
【例子】

b = dir(int)
print(b)

## 输出 
# ['__abs__', '__add__', '__and__', '__bool__', '__ceil__', '__class__',
# '__delattr__', '__dir__', '__divmod__', '__doc__', '__eq__',
# '__float__', '__floor__', '__floordiv__', '__format__', '__ge__',
# '__getattribute__', '__getnewargs__', '__gt__', '__hash__',
# '__index__', '__init__', '__init_subclass__', '__int__', '__invert__',
# '__le__', '__lshift__', '__lt__', '__mod__', '__mul__', '__ne__',
# '__neg__', '__new__', '__or__', '__pos__', '__pow__', '__radd__',
# '__rand__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__',
# '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__',
# '__round__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__',
# '__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', '__str__',
# '__sub__', '__subclasshook__', '__truediv__', '__trunc__', '__xor__',
# 'bit_length', 'conjugate', 'denominator', 'from_bytes', 'imag',
# 'numerator', 'real', 'to_bytes']

具体怎么用,需要哪些参数 (argument),查文档即可。
【bit_length()的例子】找到一个整数的二进制表示,再返回其长度。

a = 1031 # 定义一个整数数据类型的对象
print(bin(a))  # 0b10000000111
print(a.bit_length())  # 11
  • 2.浮点型
    【例子】
print(1, type(1))  # 1 <class 'int'>

print(1., type(1.))  # 1.0 <class 'float'>

a = 0.00000023
b = 2.3e-7
print(a)    # 2.3e-07
print(b)    # 2.3e-07
  • 3.布尔型
    布尔(boolean)型变量只能取两个值,True和False。当把布尔型变量用在数字运算中宏,用1和0代表True和False。
  1. 直接给变量赋值 True 和 False。
  2. 用 bool(X) 来创建变量,其中 X 可以是基本类型和容器类型。
#【例子】bool 作用在基本类型变量:X 只要不是整型 0、浮点型 0.0,bool(X) 就是 True,其余就是False。
print(type(0), bool(0), bool(1))   # <class 'int'>  False  True

print(type(10.31), bool(0.00), bool(10.31)) # <class 'float'> False True

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

# 【例子】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

确定bool(X) 的值是 True 还是 False,就看 X 是不是空,空的话就是 False,不空的话就是 True。

  • 对于基本变量,0, 0.0,’ ’ 都可认为是空的。
  • 对于容器变量,里面没元素就是空的。

1.4.2 获取数据类型

  • type(object)获取数据类型
print(type(1))  # <class 'int'>
print(type(5.2))  # <class 'float'>
print(type(True))  # <class 'bool'>
print(type('5.2'))  # <class 'str'>
  • 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

type() 不会认为子类是一种父类类型,不考虑继承关系。isinstance() 会认为子类是一种父类类型,考虑继承关系。如果要判断两个类型是否相同推荐使用 isinstance()。

1.4.3 类型转换

  • 转换为整型 int(x,base=10)
  • 转换为字符串 str(object=’ ')
  • 转换为浮点型 float(x)
    【例子】
print(int('520'))                # 520
print(int(520.52))             # 520
print(float('520.52'))         # 520.52
print(float(520))               # 520.0
print(str(10 + 10))            # '20'
print(str(10.1 + 5.2))         # '15.3'

1.5 导入包函数

  • Python 里面有很多用途广泛的包 (package),用什么你就引进 (import) 什么。包也是对象,也可以用上面提到的dir(package) 来看其属性和方法。
    ** 对象是类的具体实例**
    Q: 库(Library),包(package),模块(modual);
    Ans:库的概念比较大,但是基本上也都是相同的,都是类的集合。
    Q:SDK与API的区别|?
    Ans:API是相当于接口:我把我软件A里你需要的功能打包好,写成一个函数。你按照我说的流程,把这个函数放在软件B里,不需要看软件A的源码和功能实现过程,就能直接调用我的功能了!
    SDK–软件开发工具套件。它被开发出来是为了减少程序员工作量的,有公司开发出某种软件的某一功能,把它封装成SDK(比如美颜SDK就是能够实现美颜功能的SDK),出售给其他公司做开发用,其他公司如果想要给软件开发出某种功能,但又不想从头开始搞开发,可以付钱省事。
    你可以把SDK想象成一个虚拟的程序包,在这个程序包中有一份做好的软件功能,这份程序包几乎是全封闭的,只有一个接口可以联通外界,这个接口就是API。

例如有时候想保留浮点型的小数点后n位。可以用 decimal 包里的 Decimal 对象下的getcontext() 方法来实现。

# 导入decimal 函数
import decimal
from decimal import Decimal # 导入包里的类,赋值即创建对象 new class;
# 【例子】使1/3 保留4位,用getcontext().prec来调整精度
decimal.getcontext().prec = 4
c = Decimal(1) / Decimal(3)
print(c)     # 0.3333

1.6 print()函数

print(*objects, sep=’ ‘, end=’\n’, file=sys.stdout, flush=False)
【参数解读】

  • 将对象以字符串表示的方式格式化输出到流文件对象file里。其中所有非关键字参数都按str()方式进行转换为* * 字符串输出;
  • 关键字参数sep是实现分隔符,比如多个参数输出时想要输出中间的分隔字符;
  • 关键字参数end是输出结束时的字符,默认是换行符\n;
  • 关键字参数file是定义流输出的文件,可以是标准的系统输出sys.stdout,也可以重定义为别的文件;
  • 关键字参数flush是立即把内容输出到流文件,不作缓存。
【例子】没有参数时,每次输出默认换行
shoplist = ['apple', 'mango', 'carrot', 'banana']
print("This is printed without 'end'and 'sep'.")
for item in shoplist:
    print(item)
#【输出的结果】
# This is printed without 'end'and 'sep'.
# apple
# mango
# carrot
# banana

# 【例子】每次输出结束都用end设置的参数&结尾,并没有默认换行。
shoplist = ['apple', 'mango', 'carrot', 'banana']
print("This is printed with 'end='&''.")
for item in shoplist:
    print(item, end='&')
print('hello world')
# 【输出】
# This is printed with 'end='&''.
# apple&mango&carrot&banana&hello world
【例子】item值与'another string'两个值之间用sep设置的参数&分割。由于end参数没有设置,因此默认是输出解释后换行,即end参数的默认值为\n。
shoplist = ['apple', 'mango', 'carrot', 'banana']
print("This is printed with 'sep='&''.")
for item in shoplist:
    print(item, 'another string', sep='&')
# 【输出】
# This is printed with 'sep='&''.
# apple&another string
# mango&another string
# carrot&another string
# banana&another string

练习题

  1. 怎样对python中的代码进行注释?
    答:使用 # 为单行注释;’’’ ‘’'为区间注释;
  2. python中有哪些运算符,这些运算符的优先级是怎样的?
    答:python中运算符主要有:算术运算符、比较运算符、逻辑运算符、位运算符;
  3. python中is,is not与 ==,!=的区别是什么?
    答: is, is not 对比的是两个变量的内存地址;对于常数量是相同的,例:1,2,3,‘w’,‘e’,这样之类的。
    ==, != 对比的是两个变量的值
  4. python 中包含哪些数据类型?这些数据类型之间如何转换?
    所谓数据类型就是被分配的内存大小不同;
    答:python中有五大标准数据类型:数值型、字符串型、元组型(Tuple)、字典型(Dictionary)和列表(list)。还有一个集合(set)不常用。
    数据类型之间转换:前面加要转换的数据类型,例如:int(4.3),int(‘34’),str(23)等

思维导图

在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值