相比于C/C++,Python中使用变量差别还是很大的,刚开始也不习惯,还需要适应;
注释单行用#
多行使用''' ''' / """ """
对于变量,声明整形前不用int,直接识别;字符串也可以直接打印;
a = 12
print(a)
// 12
print("Hello world")
//Hello world
除/,python 中会有小数点;此外还多了地板除,应该是向下取整:
print(5/3)
//1.6666666666666667
print(5 // 3)
//1
比较运算符/逻辑运算符差别不大:
print(4< 2) ----False
print((1 > 3) or (9 < 21)) - ---True
print(4 ^ 5) ----100 ^ 101 ---1
Python可以直接将值转换成二进制,16进制等;
print(hex(19)) ----0x13:字符串
if_else改编的三元运算符
x, y = 4, 8
re = x if x < y else y
print(re)
Python中独有的
操作符 名称 示例
in 存在 'A' in ['A', 'B', 'C']
not in 不存在 'h' not in ['A', 'B', 'C']
is 是 "hello" is "hello"
is not 不是 "hello" is not "hello"
is, is not 对比的是两个变量的内存地址
==, != 对比的是两个变量的值
比较的两个变量,指向的都是地址不可变的类型(str等),那么is,is not 和 ==,!= 是完全等价的。
对比的两个变量,指向的是地址可变的类型(list,dict,tuple等),则两者是有区别的。
运算符的优先级
- 一元运算符优于二元运算符。例如
3 ** -2
等价于3 ** (-2)
。 - 先算术运算,后移位运算,最后位运算。例如
1 << 3 + 2 & 7
等价于(1 << (3 + 2)) & 7
二进制长度:
a = 1025
print(bin(a))
print(a.bit_length())
0b10000000001
11
Python 里面有很多用途广泛的包 (package),用什么只需要 (import) 该包。包也是对象,也可以用上面提到的dir(decimal)
来看其属性和方法。
import decimal
from decimal import Decimal
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(6)
print(b)
0.1666666666666666666666666667
decimal.getcontext().prec = 4
c = Decimal(1) / Decimal(6)
print(c)
0.1667
当把布尔型变量用在数字运算中,用 1
和 0
代表 True
和 False
。
print(True + True)
2
isinstance(object, classinfo)
判断一个对象是否是一个已知的类型。
类型转换
- 转换为整型
int(x, base=10)
- 转换为字符串
str(object='')
- 转换为浮点型
float(x)
print() 函数
print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)
将对象以字符串表示的方式格式化输出到流文件对象file里。其中所有非关键字参数都按str()方式进行转换为字符串输出;
关键字参数sep是实现分隔符,比如多个参数输出时想要输出中间的分隔字符;
关键字参数end是输出结束时的字符,默认是换行符\n;
关键字参数file是定义流输出的文件,可以是标准的系统输出sys.stdout,也可以重定义为别的文件;
关键字参数flush是立即把内容输出到流文件,不作缓存
每次输出结束都用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
shoplist = ['apple', 'mango', 'carrot', 'banana']
print("This is printed with 'end='&''.")
for item in shoplist:
print(item, end='\n')
This is printed with 'end='&''.
apple
mango
carrot
banana