Python基础(一)——变量、运算符 、数据类型及位运算
1.注释
在python中,‘#’表示单行注释;’’’ ‘’’ 或 “”" “”" 表示区间注释,如下:
单行注释
# Hello world
区间注释
'''
Hello world
'''
2.运算符
2.1 算数操作符
操作符 | 名称 |
---|---|
+ | 加 |
– | 减 |
* | 乘 |
/ | 除 |
// | 整除 |
% | 取余 |
** | 幂 |
print(1 + 1) # 2
print(2 - 1) # 1
print(3 * 4) # 12
print(3 / 4) # 0.75
print(9 // 4) # 2
print(8 % 4) # 0
print(2 ** 3) # 8
2.2 比较运算符
操作符 | 名称 |
---|---|
> | 大于 |
>= | 大于等于 |
< | 小于 |
<= | 小于等于 |
== | 等于 |
!= | 不等于 |
print(2 > 1) # True
print(2 >= 4) # False
print(1 < 2) # True
print(5 <= 2) # False
print(3 == 4) # False
print(3 != 5) # True
2.3 逻辑运算符
操作符 | 名称 |
---|---|
and | 与 |
or | 或 |
not | 非 |
print((3 > 2) and (3 < 5)) # True
print((1 > 3) or (9 < 2)) # False,两者有一个对即为True
print(not (2 > 1)) # False
2.4 位运算符
操作符 | 名称 |
---|---|
~ | 按位取反 |
& | 按位与 |
I | 按位或 |
^ | 按位异或 |
<< | 左移 |
>> | 右移 |
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
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
2.6 其他运算符
操作符 | 名称 |
---|---|
in | 存在 |
not in | 不存在 |
is | 是 |
is not | 不是 |
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
2.7 运算符的优先级
1.一元运算符优于二元运算符。例如3 ** -2等价于3 ** (-2)。
2.先算术运算,后移位运算,最后位运算。例如 1 << 3 + 2 & 7等价于 (1 << (3 + 2)) & 7。
3.逻辑运算最后结合。例如3 < 4 and 4 < 5等价于(3 < 4) and (4 < 5)。
print(-3 ** 2) # -9
print(3 ** -2) # 0.1111111111111111
print(1 << 3 + 2 & 7) # 0
print(-3 * 2 + 5 / -2 - 4) # -12.5
print(3 < 4 and 4 < 5) # True
3. 变量和赋值
1.在使用变量之前,需要对其先赋值。
2.变量名可以包括字母、数字、下划线、但变量名不能以数字开头。
3.Python 变量名是大小写敏感的
teacher = "老马的程序人生"
print(teacher) # 老马的程序人生
#########
first = 2
second = 3
third = first + second
print(third) # 5
#########
myTeacher = "老马的程序人生"
yourTeacher = "小马的程序人生"
ourTeacher = myTeacher + ',' + yourTeacher
print(ourTeacher) # 老马的程序人生,小马的程序人生
4.数据类型和转化
类型 | 名称 |
---|---|
int | 整型 |
float | 浮点型 |
bool | 布尔型 |
a = 1031
print(a, type(a)) # 判断a的类型
print(isinstance(a, int)) # True,判断a是否为整型
类型转化
1.转换为整型 int(x, base=10)
2.转换为字符串 str(object=’’)
3.转换为浮点型 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