1 变量、运算符与数据类型
1.1 注释
在python中主要用“#”进行单行注释,三个单引号’’’ ‘’'或三个双引号""" “”"进行多行注释,非常简单,不再赘述。常用快捷键:
Pycharm中()
多行注释:
选中代码后 快捷键 Ctrl + /
单行注释:也可以选中或光标停留在该行 Ctrl + /
1.2 运算符
1.2.1 算术运算符
常见的有加(+)、减(-)、乘(*)、除(/)、整除(地整除)(//)、取余(%)、幂(**)
print(11//3) #3
print(2**3) #8
1.2.2 比较运算符
比较运算符有大于(>)、大于等于(>=)、小于(<)、小于等于(<=)、等于(==)、不等于(!=)
print(2<3) #True
print(1!=1) #False
1.2.3 逻辑运算符
逻辑运算符有与(and)、或(or)、非(not)
print((2<3) and (3<5)) #True
print((1>3) or (3<5) ) #True
1.2.4 位运算符
重点看下按位左移<<,和按位右移>>操作。
11 >> 2
相当于11的二进制形式00 00 10 11 向右移两位得到00 00 00 10(2)
可以看成是11//4(11地板除2^2)
向右移n位就可以看成地板除2^n,按位移的方法比地板除速度要快。
同理,对于按位左移操作,可以看成是地板除2^n。
1.2.5 三元运算符
三元运算又称三目运算,是对简单的条件语句的简写,如:
简单条件语句:
if 条件成立:
val = 1
else:
val = 2
改成三元运算:
val = 1 if 条件成立 else 2
这样就可以大大简化代码的长度。
1.2.6 其他运算符
操作符 | 名称 |
---|---|
is | 是 |
is not | 不是 |
in | 存在 |
not in | 不存在 |
这里需要进行进一步强调,is,is not对比的是两个变量的内存地址.
in,not in是在指定序列中找寻某个值是否在序列中。
a = 2
a is 2
True
我们可以把变量a和数字2的内存地址读出来进行比较
id(a)
id(2)
我们会发现他们的内存地址相同,因而为真True。
a = ["hello"]
b = ["hello"]
print(a is b, a==b)
# False True
a is b显示为False,是因为a,b指向的地址是可变类型,所以二者不相等。而等于号对比的是两个变量的值。我们也可以用上面的方法,查看a变量与b变量的地址,进行比较。
1.2.7 运算优先级:
所有的数学运算都是从左向右进行的,Python 语言中的大部分运算符也是从左向右结合的,只有单目运算符、赋值运算符和三目运算符例外,它们是从右向左结合的,也就是说,它们是从右向左运算的。
几条运算符优先级原则:
- 一元运算符优于二元运算符。如正负号。
- 先算术运算,后移位运算,最后位运算。
- 逻辑运算最后结合
1.3 变量和赋值
- 在使用变量之前,需要对其先赋值。
- 变量名可以包括字母、数字、下划线、但变量名不能以数字开头。
- Python 变量名是大小写敏感的,foo != Foo。
- 变量名尽量有含义,多层含义可以用驼峰式,或下划线形式进行连接如myTeacher, your_teacher等等。
teacher = '老马'
student = '小马'
print(teacher+student)
1.4 数据类型与转换
1.4.1 整型<class ‘int’>
a = 1031
print(a,type(a)) #type()用来查看变量类型
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']
通过print可看出a的值,以及类 (class) 是int。Python 里面万物皆对象(object),整型也不例外,只要是对象,就有相应的属性(attributes)和方法(methods)。对它们有个大概印象就可以了,具体怎么用,需要哪些参数(argument),还需要查文档。看个bit_length的例子。
#找到一个整数的二进制表示,并返回其长度
a =1024
print(bin(a)) #0b10000000000
print(a.bit_length()) #11
1.4.2 浮点型<class ‘float’>
print(1., type(1.))
# 1.0 <class 'float'>
有时候我们想保留浮点型的小数点后 n
位。可以用 decimal
包里的 Decimal
对象和 getcontext()
方法来实现。
import decimal
from decimal import Decimal
Python 里面有很多用途广泛的包 (package),用什么你就引进 (import) 什么。包也是对象,也可以用上面提到的dir(decimal)
来看其属性和方法。
#【例子】`getcontext()` 显示了 `Decimal` 对象的默认精度值是 28 位 (`prec=28`)。
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/3 保留 4 位,用 `getcontext().prec` 来调整精度。
decimal.getcontext().prec = 4
c = Decimal(1) / Decimal(3)
print(c)
# 0.3333
1.4.3 布尔型<class ‘bool’>
布尔 (boolean) 型变量只能取两个值,True
和 False
。当把布尔型变量用在数字运算中,用 1
和 0
代表 True
和 False
。
除了直接给变量赋值 True
和 False
,还可以用 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.4获取类型信息
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()
。
class A:
pass
class B(A):
pass
print(isinstance(A(), A)) # returns True
print(type(A()) == A) # returns True
print(isinstance(B(), A)) # returns True
print(type(B()) == A) # returns False
1.4.5 类型转换
- 转换为整型
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
以上只是最简单的类型转换,python中类型转换知识点蛮多的,有兴趣的,可以参考这篇去理解下:https://zhuanlan.zhihu.com/p/39610331
1.5 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
参考文献:
- https://www.runoob.com/python3/python3-tutorial.html
- https://www.bilibili.com/video/av4050443
- https://mp.weixin.qq.com/s/DZ589xEbOQ2QLtiq8mP1qQ
- https://www.cnblogs.com/OliverQin/p/7781019.html
练习题:
- 怎样对python中的代码进行注释?
答:对于单行注释,可以用“#”,对于多行注释,可以用三个单引号’’’ ‘’'或三个双引号""" “”"进行注释。 - python有哪些运算符,这些运算符的优先级是怎样的?
参见1.2.7 节运算优先级 - python 中
is
,is not
与==
,!=
的区别是什么?
最主要的区别是is
,is not
比较的是变量的地址是否相同,而==
,!=
比较的是变量的值是否相同。 - python 中包含哪些数据类型?这些数据类型之间如何转换?
int(x [,base ]) 将x转换为一个整数 int ('0x88',16)将16进制的0x88转换成整数
long(x [,base ]) 将x转换为一个长整数
float(x ) 将x转换到一个浮点数
complex(real [,imag ]) 创建一个复数
str(x ) 将对象 x 转换为字符串
repr(x ) 将对象 x 转换为表达式字符串
eval(str ) 用来计算在字符串中的有效Python表达式,并返回一个对象
tuple(s ) 将序列 s 转换为一个元组
list(s ) 将序列 s 转换为一个列表
chr(x ) 将一个整数转换为一个字符
unichr(x ) 将一个整数转换为Unicode字符
ord(x ) 将一个字符转换为它的整数值
hex(x ) 将一个整数转换为一个十六进制字符串
oct(x ) 将一个整数转换为一个八进制字符串