1.數值數據類型
python內置函數type()用於判斷對象的類型
2.運算符
操作符 | 操作 |
---|---|
+ | 加 |
- | 減 |
* | 乘 |
/ | 除 |
** | 指數 |
abs() | 絕對值 |
// | 取整 |
% | 取餘 |
在大多數情況下,對float的操作產生float,對int的操作產生int。大多數時候,我們甚至不必擔心正在操作什麼類型的操作。
3.類型轉換和舍入
int() 轉換成整型,也可以操作數字字符串,int("123")
float() 轉換成浮點型
round(n,m) 保留m位
round(n) 保留1位
4.math庫
Python提供了一個特殊的庫(模塊)‘math’,提供了許多其他有用的數學函數。
@ 求二次方程的根
def main():
print("This program finds the real solutions to a quadratic")
print()
a = float(input("Enter coefficient a: "))
b = float(input("Enter coefficient b: "))
c = float(input("Enter coefficient c: "))
discRoot = math.sqrt(b*b - 4*a*c)
root1 = (-b + discRoot) / (2 * a)
root1 = (-b - discRoot) / (2 * a)
print()
print("The solutions are:",root1,',',root2)
Python | 描述 |
---|---|
pi | pi的近似值 |
e | e的近似值 |
sqrt(x) | 開根號 |
sin(x),cos(x),tan(x) | 三角函數 |
asin(x),acos(x),atan(x) | 反三角函數 |
log(x) | ln x |
log10(x) | log x |
exp(x) | e^x |
ceil(x) | 最小的>=x的整數 |
floor(x) | 最大的<=x的整數 |
@ n的階乘
def main():
n = input("Enter n:")
n = int(n)
result = 1
for i in range(n+1)
result = result * i
print(result )
@ range()函數的另一種用法
@ range(a,b,x):產生a到b-1以x爲步長的序列
def main():
n = input("Enter n:")
n = int(n)
result = 1
for i in range(n,0,-1) #i = [n n-1 n-2 ... 1]
result = result * i
print(result )