python作为计算器(数学用法)

1.基本的加减乘除与取余运算

>>> print(5+10)
15
>>> print(5-10)
-5
>>> print(5*10)
50
>>> print(10/5)
2.0
>>> print(5%3)
2

补充:如果想保留位数需要用到round函数(如果不指定的话默认取整)

>>> print(100/10)
10.0
>>> print(round(100/10))
10
>>> print(round(100/10,3))
10.0
>>> print(round(100/3,3))
33.333

2.求n次方与求平方根

>>> print(5%3)
2
>>> print(5**3)
125
>>> print(125**(1/3))
5.0
>>> print(2**4)
16
>>> print(16**(1/2))
4.0
>>>

3.math函数库的使用

引入math库并查看PI的值

>>> import math
>>> math.pi
3.141592653589793

(1)求正弦余弦函数

>>> math.sin(math.pi/2)
1.0
>>> math.cos(math.pi/4)
0.7071067811865476
>>> math.tan(math.pi/4)
0.9999999999999999
>>>

(2)上取整与下取整

>>> math.floor(5.225)
5
>>> math.ceil(5.225)
6

练习:一道应用题

苹果5元一斤,葡萄15元一斤,卖了一斤苹果2.5斤葡萄,问总共花了多少钱?

解:

>>> #苹果花费
...
>>> #葡萄花费
...
>>> print(5*1)
5
>>> print(15*2.5)
37.5
>>> #总花费
...
>>> print(5+37.5)
42.5

解法二:

>>> apple_price = 5
>>> apple_weight = 1
>>> putao_price = 15
>>> putao_weight = 2.5
>>> #苹果花费
... print(apple_price*apple_weight)
5
>>> #葡萄花费
... print(putao_price*putao_weight)
37.5
>>> #总花费
... print(5+37.5)
42.5
>>>
>>> putao_toast = putao_price*putao_weight
>>> apple_toast = apple_price*apple_weight
>>> print(putao_toast + apple_toast)
42.5

解法三:利用增强的格式化字符串函数 format

>>> "葡萄的总价是{},苹果的总价是{},总共花费{}".format(putao_toast,apple_toast,pu
tao_toast+apple_toast)
'葡萄的总价是37.5,苹果的总价是5,总共花费42.5'

{}代表取参数,有几个{},传几个参数,按顺序取参数

原文地址:https://www.cnblogs.com/qlqwjy/p/8450093.html