简单数据类型
#int
int1 = 10_000_000_000;
int2 = 10000000000;
int3 = 0xa1b2_c3d4;
print(int1,int2,int3);
#10000000000 10000000000 2712847316
#float
#Str
str1 = "this is a str";
str2 = """ it's joke
this is a str too
""";
print(str1);
print(str2);
#bool
tVar = 100 == 100;
fVar = 100 == 200;
print(tVar,fVar);
print(tVar and fVar);
print(tVar or fVar);
print(not tVar);
# None None是一个特殊的空值
格式化
# 字符串格式化 %d %f %s %x
print("%2d-%02d" % (3,1))
print('%.2f' % 3.1415)
#format()
print('Hello,{0},成绩提升{1:.1f}%'.format('小明',17.152))
#f-string
r=2.5
s=3.14 * r ** 2
print(f'The area of a circle with radius {r} is {s:.2f}')
s1=72
s2=85
print('小明成绩上涨%.1f %%' % ((s2-s1) / s1 * 100))
字符编码
# 字符编码 Python 3版本中,字符串是以Unicode编码的
# print('包含中文的str');
# 转换 ord()获取字符ASCII编码 chr()ASCII编码转为字符
# print(ord('A'))
# print(chr(70))
# 内存中以字符存储, 网络传输以字节传输
x = b'ABC'
# print(x);
c = "ABC".encode("ascii");
# d = "中文".encode("ascii");
e = "中文字符".encode("utf-8");
print(c,e)
# decode 转换前后的数据含义是一致的,前者表示字节, 后者表示字符
decodeC = b'ABC'.decode("ascii");
decodeE = b'\xe4\xb8\xad\xe6\x96\x87\xe5\xad\x97\xe7\xac\xa6'.decode("utf-8")
print(decodeC,decodeE);
# gbk转换为2字节, utf-8转换为3字节
print(len("ABC"),len("中文字符"))
print(len(b'ABC'),len(b'\xe4\xb8\xad\xe6\x96\x87\xe5\xad\x97\xe7\xac\xa6'))
list和truple
classmate = ['zhangsan','lisi','wangwu']
print(classmate,len(classmate),classmate[0], classmate[-1])
classmate.append('liuxing')
print(classmate, classmate[-1])
print( classmate.pop(-1),classmate)
t1 = (1,[2,3],3)
t1[1][0]=5; t1[1][1]=6;
# t1[2]=9;
t2=(1,)
print(t1,t2);
条件判断
age = int( input('age:') );
if (age > 18) : print('adult');
elif (age > 12) : print("tennager")
else : print('kid')
height = 1.75
weight = 80.5
bmi = weight / (height ** 2)
if bmi < 18.5 : print('过轻')
elif bmi <= 25 : print('正常')
elif bmi <= 28 : print('过重')
elif bmi <= 32 : print('肥胖')
else : print('严重肥胖')
loop
names = ['Michael', 'Bob', 'Tracy']
for name in names:
print(name)
for循环
range 生成序列 [0,101)
sum = 0
for x in range(101):
sum = sum + x
print(sum)
while 循环
只要条件满足,就不断循环,条件不满足时退出循环
sum = 0
n = 99
while n > 0:
sum = sum + n
n = n - 2
print(sum)
break和continue
n = 1
while n <= 100:
if n > 10: # 当n = 11时,条件满足,执行break语句
break # break语句会结束当前循环
print(n)
n = n + 1
print('END')
n = 0
while n < 10:
n = n + 1
if n % 2 == 0: # 如果n是偶数,执行continue语句
continue # continue语句会直接继续下一轮循环,后续的print()语句不会执行
print(n)
dict和set
# dict 中key不可变(str, int), 类似于map, 无顺序,空间占用大
#dict 索引访问, get(key)
d = {'Michael': 95, 'Bob': 75, 'Tracy': 85}
print(d['Michael'],d.get('Michael'));
# 判断key是否存在
print('key' in d)
print(d.get('key','Not Exist'))
# 删除
print(d.pop('Bob'),d);
# set和dict类似,也是一组key的集合,但不存储value; 元素不可变
s = set([1,2,3])
print(s)
# 操作set元素
print(s.add(66),s)
print(s.remove(66),s)
# set与set可以交并补
s1= set([1,2,3])
s2= set([2,3,4])
print(s1 & s2 , s1 | s2)
ls = [7,8,9]
# s1.add(ls) 可变对象放入set报错
# 不可变对象
# 调用对象自身的任意方法,也不会改变该对象自身的内容。相反,这些方法会创建新的对象并返回,这样,就保证了不可变对象本身永远是不可变
|