1. 程式人生 > >python作為計算器(數學用法)

python作為計算器(數學用法)

price 取余 乘除 pos 增強 int 正弦 順序 pri

1.基本的加減乘除與取余運算

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

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

{}代表取參數,有幾個{},傳幾個參數,按順序取參數

python作為計算器(數學用法)