Python基础(一)——变量、运算符 、数据类型及位运算

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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值