文章目录
打印数据类型:type
>>> print(type(a))
<class 'int'>
- int():将一个数值或字符串转换成整数,可以指定进制。
- float():将一个字符串转换成浮点数。
- str():将指定的对象转换成字符串形式,可以指定编码。
- chr():将整数转换成该编码对应的字符串(一个字符)。
- ord():将字符串(一个字符)转换成对应的编码(整数)。
整除
- 自然除法:能整除则整除,不能整除以浮点数的方式返回结果
- 运算符//:对不能整除的向下取整
- 取整函数int:对于整数直接返回原值,对于浮点数返回其整数部分
- 四舍五入取偶函数round():对于整数直接返回原值,对于浮点数,进行四舍五入,并且向偶数取整。另外
both round(0.5) and round(-0.5) are 0, and round(1.5) is 2
- 向下取整floor():见名知意,(-1,1)取0;(1,2)取1;(n,n+1)取n;(-n,-n-1)n>0取-n-1
- 向上取整ceil():用法与floor相反,并且都需要导入math模块
>>> 1/2 #0.5
>>> 1/3 #0.3333333333333333
>>> 1//2 #0
>>> 1//3 #0
>>> 7//2 #3
>>> -7//2 #-4
>>> -(7//2) #-3
>>> int(1.9999) #1
>>> int(1.0) #1
>>> round(1.5) #2
>>> round(-1.5) #-2
>>> round(0.5) #0
>>> round(0.500001) #1
import math
math.floor(1.9999) #1
math.floor(1.0) #1
math.floor(-3.4) #-4
math.ceil(2.1) #3
math.ceil(-2.999) #2
常用的数值处理函数
min() :对象可以是可迭代对象或者是一列对象
max() :
pow(x,y):幂运算,x**y(x的y次方)
math.sqrt(x):开方运算x**0.5
bin():将十进制整型数值转换位二进制,返回字符串,类似于'0b1010'
oct():将十进制整型数值转换为八进制,返回字符串,类似于'0o12'
hex():将十进制整型数值转换为十六进制,返回字符串,类似于'0xa'
math.pi:引用π的值
math.e:引用e的值
另外还有对数函数和三角函数等
类型转换
a=int(input('a= '))
b=int(input('b= '))
print('%d + %d = %d' % (a,b,a+b))
赋值运算与复合赋值运算
a = 10
b = 3
a += b # 相当于:a = a + b
a *= a + 2 # 相当于:a = a * (a + 2)
print(a) # 想想这里会输出什么
笔记运算符与逻辑运算
flag0 = 1 == 1
flag1 = 3 > 2
flag2 = 2 < 1
flag3 = flag1 and flag2
flag4 = flag1 or flag2
flag5 = not (1 != 2)
print('flag0 =', flag0) # flag0 = True
print('flag1 =', flag1) # flag1 = True
print('flag2 =', flag2) # flag2 = False
print('flag3 =', flag3) # flag3 = False
print('flag4 =', flag4) # flag4 = True
print('flag5 =', flag5) # flag5 = False
print(flag1 is True) # True 由于flag1是假,因此括号中的为真,所以输出True
print(flag2 is not False) # False
将华氏温度转换为摄氏温度
F=float(input('请输入华氏温度:')) #默认input获取到的输入是string类型,因此这里需要进行显式转换
f=(F - 32) / 1.8
print('摄氏温度为:%.3f' % (f)) #%.3f默认保留三位小数
计算圆的面积和周长
import math
r=float(input('请输入圆的半径:')) #显式转换
S=math.pi*r**2
L=2*math.pi*r
print('圆的面积为:%.3f' % S)
print('圆的周长为:%.3f' % L)
计算年份
year=float(input('请输入年份:'))
if (year % 4 == 0 and year % 100 != 0) or year % 400 == 0:
print('%d is a special Year' % year)
else:
print('%d is not a special Year' % year)
来源:CSDN
作者:ppplaybook
链接:https://blog.csdn.net/weixin_42768584/article/details/103597600